1 module stb_vorbis;
2 
3 // Ogg Vorbis audio decoder - v1.10 - public domain
4 // http://nothings.org/stb_vorbis/
5 //
6 // Original version written by Sean Barrett in 2007.
7 //
8 // Originally sponsored by RAD Game Tools. Seeking sponsored
9 // by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software,
10 // Aras Pranckevicius, and Sean Barrett.
11 //
12 // LICENSE
13 //
14 //   See end of file for license information.
15 //
16 // Limitations:
17 //
18 //   - floor 0 not supported (used in old ogg vorbis files pre-2004)
19 //   - lossless sample-truncation at beginning ignored
20 //   - cannot concatenate multiple vorbis streams
21 //   - sample positions are 32-bit, limiting seekable 192Khz
22 //       files to around 6 hours (Ogg supports 64-bit)
23 //
24 // Feature contributors:
25 //    Dougall Johnson (sample-exact seeking)
26 //
27 // Bugfix/warning contributors:
28 //    Terje Mathisen     Niklas Frykholm     Andy Hill
29 //    Casey Muratori     John Bolton         Gargaj
30 //    Laurent Gomila     Marc LeBlanc        Ronny Chevalier
31 //    Bernhard Wodo      Evan Balster        alxprd@github
32 //    Tom Beaumont       Ingo Leitgeb        Nicolas Guillemot
33 //    Phillip Bennefall  Rohit               Thiago Goulart
34 //    manxorist@github   saga musix
35 //
36 // Partial history:
37 //    1.10    - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
38 //    1.09    - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
39 //    1.08    - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
40 //                           avoid discarding last frame of audio data
41 //    1.07    - 2015/01/16 - fixed some warnings, fix mingw, const-correct API
42 //                           some more crash fixes when out of memory or with corrupt files
43 //    1.06    - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
44 //                           some crash fixes when out of memory or with corrupt files
45 //                           fix some inappropriately signed shifts
46 //    1.05    - 2015/04/19 - don't define __forceinline if it's redundant
47 //    1.04    - 2014/08/27 - fix missing const-correct case in API
48 //    1.03    - 2014/08/07 - warning fixes
49 //    1.02    - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows
50 //    1.01    - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct)
51 //    1.0     - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
52 //                           (API change) report sample rate for decode-full-file funcs
53 //    0.99996 -            - bracket #include <malloc.h> for macintosh compilation
54 //    0.99995 -            - avoid alias-optimization issue in float-to-int conversion
55 //
56 // See end of file for full version history.
57 // D translation by Ketmar // Invisible Vector
58 // stolen by adam and module renamed.
59 // Stolen by jordan4ibanez and further modified.
60 /++
61 	Port of stb_vorbis to D. Provides .ogg audio file reading capabilities.
62     See [arsd.simpleaudio] for code that can use this to actually load and play the file.
63 +/
64 
65 import core.stdc.stdio : FILE;
66 
67 version(Windows)
68 	extern(C) int lrintf(float f) { return cast(int) f; }
69 
70 nothrow /*@trusted*/:
71 @nogc { // code block, as c macro helper is not @nogc; yet it's CTFE-only
72 // import it here, as druntime has no `@nogc` on it (for a reason)
73 private extern(C) void qsort (void* base, size_t nmemb, size_t size, int function(in void*, in void*) compar);
74 
75 
76 //////////////////////////////////////////////////////////////////////////////
77 //
78 //  HEADER BEGINS HERE
79 //
80 
81 ///////////   THREAD SAFETY
82 
83 // Individual VorbisDecoder* handles are not thread-safe; you cannot decode from
84 // them from multiple threads at the same time. However, you can have multiple
85 // VorbisDecoder* handles and decode from them independently in multiple thrads.
86 
87 
88 ///////////   MEMORY ALLOCATION
89 
90 // normally stb_vorbis uses malloc() to allocate memory at startup,
91 // and alloca() to allocate temporary memory during a frame on the
92 // stack. (Memory consumption will depend on the amount of setup
93 // data in the file and how you set the compile flags for speed
94 // vs. size. In my test files the maximal-size usage is ~150KB.)
95 //
96 // You can modify the wrapper functions in the source (setup_malloc,
97 // setup_temp_malloc, temp_malloc) to change this behavior, or you
98 // can use a simpler allocation model: you pass in a buffer from
99 // which stb_vorbis will allocate _all_ its memory (including the
100 // temp memory). "open" may fail with a VORBIS_outofmem if you
101 // do not pass in enough data; there is no way to determine how
102 // much you do need except to succeed (at which point you can
103 // query get_info to find the exact amount required. yes I know
104 // this is lame).
105 //
106 // If you pass in a non-null buffer of the type below, allocation
107 // will occur from it as described above. Otherwise just pass null
108 // to use malloc()/alloca()
109 
110 public struct STBVorbisAlloc {
111   ubyte* alloc_buffer;
112   int alloc_buffer_length_in_bytes;
113 }
114 
115 
116 ///////////   FUNCTIONS USEABLE WITH ALL INPUT MODES
117 
118 /*
119 public struct stb_vorbis_info {
120   uint sample_rate;
121   int channels;
122 
123   uint setup_memory_required;
124   uint setup_temp_memory_required;
125   uint temp_memory_required;
126 
127   int max_frame_size;
128 }
129 */
130 
131 
132 /* ************************************************************************** *
133 // get general information about the file
134 stb_vorbis_info stb_vorbis_get_info (VorbisDecoder* f);
135 
136 // get the last error detected (clears it, too)
137 int stb_vorbis_get_error (VorbisDecoder* f);
138 
139 // close an ogg vorbis file and free all memory in use
140 void stb_vorbis_close (VorbisDecoder* f);
141 
142 // this function returns the offset (in samples) from the beginning of the
143 // file that will be returned by the next decode, if it is known, or -1
144 // otherwise. after a flush_pushdata() call, this may take a while before
145 // it becomes valid again.
146 // NOT WORKING YET after a seek with PULLDATA API
147 int stb_vorbis_get_sample_offset (VorbisDecoder* f);
148 
149 // returns the current seek point within the file, or offset from the beginning
150 // of the memory buffer. In pushdata mode it returns 0.
151 uint stb_vorbis_get_file_offset (VorbisDecoder* f);
152 
153 
154 ///////////   PUSHDATA API
155 
156 // this API allows you to get blocks of data from any source and hand
157 // them to stb_vorbis. you have to buffer them; stb_vorbis will tell
158 // you how much it used, and you have to give it the rest next time;
159 // and stb_vorbis may not have enough data to work with and you will
160 // need to give it the same data again PLUS more. Note that the Vorbis
161 // specification does not bound the size of an individual frame.
162 
163 // create a vorbis decoder by passing in the initial data block containing
164 //    the ogg&vorbis headers (you don't need to do parse them, just provide
165 //    the first N bytes of the file--you're told if it's not enough, see below)
166 // on success, returns an VorbisDecoder, does not set error, returns the amount of
167 //    data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
168 // on failure, returns null on error and sets *error, does not change *datablock_memory_consumed
169 // if returns null and *error is VORBIS_need_more_data, then the input block was
170 //       incomplete and you need to pass in a larger block from the start of the file
171 VorbisDecoder* stb_vorbis_open_pushdata (
172               ubyte* datablock, int datablock_length_in_bytes,
173               int* datablock_memory_consumed_in_bytes,
174               int* error,
175               STBVorbisAlloc* alloc_buffer
176             );
177 
178 // decode a frame of audio sample data if possible from the passed-in data block
179 //
180 // return value: number of bytes we used from datablock
181 //
182 // possible cases:
183 //     0 bytes used, 0 samples output (need more data)
184 //     N bytes used, 0 samples output (resynching the stream, keep going)
185 //     N bytes used, M samples output (one frame of data)
186 // note that after opening a file, you will ALWAYS get one N-bytes, 0-sample
187 // frame, because Vorbis always "discards" the first frame.
188 //
189 // Note that on resynch, stb_vorbis will rarely consume all of the buffer,
190 // instead only datablock_length_in_bytes-3 or less. This is because it wants
191 // to avoid missing parts of a page header if they cross a datablock boundary,
192 // without writing state-machiney code to record a partial detection.
193 //
194 // The number of channels returned are stored in *channels (which can be
195 // null--it is always the same as the number of channels reported by
196 // get_info). *output will contain an array of float* buffers, one per
197 // channel. In other words, (*output)[0][0] contains the first sample from
198 // the first channel, and (*output)[1][0] contains the first sample from
199 // the second channel.
200 int stb_vorbis_decode_frame_pushdata (
201       VorbisDecoder* f, ubyte* datablock, int datablock_length_in_bytes,
202       int* channels,   // place to write number of float * buffers
203       float*** output, // place to write float ** array of float * buffers
204       int* samples     // place to write number of output samples
205     );
206 
207 // inform stb_vorbis that your next datablock will not be contiguous with
208 // previous ones (e.g. you've seeked in the data); future attempts to decode
209 // frames will cause stb_vorbis to resynchronize (as noted above), and
210 // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
211 // will begin decoding the _next_ frame.
212 //
213 // if you want to seek using pushdata, you need to seek in your file, then
214 // call stb_vorbis_flush_pushdata(), then start calling decoding, then once
215 // decoding is returning you data, call stb_vorbis_get_sample_offset, and
216 // if you don't like the result, seek your file again and repeat.
217 void stb_vorbis_flush_pushdata (VorbisDecoder* f);
218 
219 
220 //////////   PULLING INPUT API
221 
222 // This API assumes stb_vorbis is allowed to pull data from a source--
223 // either a block of memory containing the _entire_ vorbis stream, or a
224 // FILE* that you or it create, or possibly some other reading mechanism
225 // if you go modify the source to replace the FILE* case with some kind
226 // of callback to your code. (But if you don't support seeking, you may
227 // just want to go ahead and use pushdata.)
228 
229 // decode an entire file and output the data interleaved into a malloc()ed
230 // buffer stored in *output. The return value is the number of samples
231 // decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
232 // When you're done with it, just free() the pointer returned in *output.
233 int stb_vorbis_decode_filename (const(char)* filename, int* channels, int* sample_rate, short** output);
234 int stb_vorbis_decode_memory (const(ubyte)* mem, int len, int* channels, int* sample_rate, short** output);
235 
236 // create an ogg vorbis decoder from an ogg vorbis stream in memory (note
237 // this must be the entire stream!). on failure, returns null and sets *error
238 VorbisDecoder* stb_vorbis_open_memory (const(ubyte)* data, int len, int* error, STBVorbisAlloc* alloc_buffer);
239 
240 // create an ogg vorbis decoder from a filename via fopen(). on failure,
241 // returns null and sets *error (possibly to VORBIS_file_open_failure).
242 VorbisDecoder* stb_vorbis_open_filename (const(char)* filename, int* error, STBVorbisAlloc* alloc_buffer);
243 
244 // create an ogg vorbis decoder from an open FILE*, looking for a stream at
245 // the _current_ seek point (ftell). on failure, returns null and sets *error.
246 // note that stb_vorbis must "own" this stream; if you seek it in between
247 // calls to stb_vorbis, it will become confused. Morever, if you attempt to
248 // perform stb_vorbis_seek_*() operations on this file, it will assume it
249 // owns the _entire_ rest of the file after the start point. Use the next
250 // function, stb_vorbis_open_file_section(), to limit it.
251 VorbisDecoder* stb_vorbis_open_file (FILE* f, int close_handle_on_close, int* error, STBVorbisAlloc* alloc_buffer);
252 
253 // create an ogg vorbis decoder from an open FILE*, looking for a stream at
254 // the _current_ seek point (ftell); the stream will be of length 'len' bytes.
255 // on failure, returns null and sets *error. note that stb_vorbis must "own"
256 // this stream; if you seek it in between calls to stb_vorbis, it will become
257 // confused.
258 VorbisDecoder* stb_vorbis_open_file_section (FILE* f, int close_handle_on_close, int* error, STBVorbisAlloc* alloc_buffer, uint len);
259 
260 // these functions seek in the Vorbis file to (approximately) 'sample_number'.
261 // after calling seek_frame(), the next call to get_frame_*() will include
262 // the specified sample. after calling stb_vorbis_seek(), the next call to
263 // stb_vorbis_get_samples_* will start with the specified sample. If you
264 // do not need to seek to EXACTLY the target sample when using get_samples_*,
265 // you can also use seek_frame().
266 int stb_vorbis_seek_frame (VorbisDecoder* f, uint sample_number);
267 int stb_vorbis_seek (VorbisDecoder* f, uint sample_number);
268 
269 // this function is equivalent to stb_vorbis_seek(f, 0)
270 int stb_vorbis_seek_start (VorbisDecoder* f);
271 
272 // these functions return the total length of the vorbis stream
273 uint stb_vorbis_stream_length_in_samples (VorbisDecoder* f);
274 float stb_vorbis_stream_length_in_seconds (VorbisDecoder* f);
275 
276 // decode the next frame and return the number of samples. the number of
277 // channels returned are stored in *channels (which can be null--it is always
278 // the same as the number of channels reported by get_info). *output will
279 // contain an array of float* buffers, one per channel. These outputs will
280 // be overwritten on the next call to stb_vorbis_get_frame_*.
281 //
282 // You generally should not intermix calls to stb_vorbis_get_frame_*()
283 // and stb_vorbis_get_samples_*(), since the latter calls the former.
284 int stb_vorbis_get_frame_float (VorbisDecoder* f, int* channels, float*** output);
285 
286 // decode the next frame and return the number of *samples* per channel.
287 // Note that for interleaved data, you pass in the number of shorts (the
288 // size of your array), but the return value is the number of samples per
289 // channel, not the total number of samples.
290 //
291 // The data is coerced to the number of channels you request according to the
292 // channel coercion rules (see below). You must pass in the size of your
293 // buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
294 // The maximum buffer size needed can be gotten from get_info(); however,
295 // the Vorbis I specification implies an absolute maximum of 4096 samples
296 // per channel.
297 int stb_vorbis_get_frame_short_interleaved (VorbisDecoder* f, int num_c, short* buffer, int num_shorts);
298 int stb_vorbis_get_frame_short (VorbisDecoder* f, int num_c, short** buffer, int num_samples);
299 
300 // Channel coercion rules:
301 //    Let M be the number of channels requested, and N the number of channels present,
302 //    and Cn be the nth channel; let stereo L be the sum of all L and center channels,
303 //    and stereo R be the sum of all R and center channels (channel assignment from the
304 //    vorbis spec).
305 //        M    N       output
306 //        1    k      sum(Ck) for all k
307 //        2    *      stereo L, stereo R
308 //        k    l      k > l, the first l channels, then 0s
309 //        k    l      k <= l, the first k channels
310 //    Note that this is not _good_ surround etc. mixing at all! It's just so
311 //    you get something useful.
312 
313 // gets num_samples samples, not necessarily on a frame boundary--this requires
314 // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
315 // Returns the number of samples stored per channel; it may be less than requested
316 // at the end of the file. If there are no more samples in the file, returns 0.
317 int stb_vorbis_get_samples_float_interleaved (VorbisDecoder* f, int channels, float* buffer, int num_floats);
318 int stb_vorbis_get_samples_float (VorbisDecoder* f, int channels, float** buffer, int num_samples);
319 
320 // gets num_samples samples, not necessarily on a frame boundary--this requires
321 // buffering so you have to supply the buffers. Applies the coercion rules above
322 // to produce 'channels' channels. Returns the number of samples stored per channel;
323 // it may be less than requested at the end of the file. If there are no more
324 // samples in the file, returns 0.
325 int stb_vorbis_get_samples_short_interleaved (VorbisDecoder* f, int channels, short* buffer, int num_shorts);
326 int stb_vorbis_get_samples_short (VorbisDecoder* f, int channels, short** buffer, int num_samples);
327 */
328 
329 ////////   ERROR CODES
330 
331 public enum STBVorbisError {
332   no_error,
333 
334   need_more_data = 1,    // not a real error
335 
336   invalid_api_mixing,    // can't mix API modes
337   outofmem,              // not enough memory
338   feature_not_supported, // uses floor 0
339   too_many_channels,     // STB_VORBIS_MAX_CHANNELS is too small
340   file_open_failure,     // fopen() failed
341   seek_without_length,   // can't seek in unknown-length file
342 
343   unexpected_eof = 10,   // file is truncated?
344   seek_invalid,          // seek past EOF
345 
346   // decoding errors (corrupt/invalid stream) -- you probably
347   // don't care about the exact details of these
348 
349   // vorbis errors:
350   invalid_setup = 20,
351   invalid_stream,
352 
353   // ogg errors:
354   missing_capture_pattern = 30,
355   invalid_stream_structure_version,
356   continued_packet_flag_invalid,
357   incorrect_stream_serial_number,
358   invalid_first_page,
359   bad_packet_type,
360   cant_find_last_page,
361   seek_failed,
362 }
363 //
364 //  HEADER ENDS HERE
365 //
366 //////////////////////////////////////////////////////////////////////////////
367 
368 
369 // global configuration settings (e.g. set these in the project/makefile),
370 // or just set them in this file at the top (although ideally the first few
371 // should be visible when the header file is compiled too, although it's not
372 // crucial)
373 
374 // STB_VORBIS_NO_INTEGER_CONVERSION
375 //     does not compile the code for converting audio sample data from
376 //     float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
377 //version = STB_VORBIS_NO_INTEGER_CONVERSION;
378 
379 // STB_VORBIS_NO_FAST_SCALED_FLOAT
380 //      does not use a fast float-to-int trick to accelerate float-to-int on
381 //      most platforms which requires endianness be defined correctly.
382 //version = STB_VORBIS_NO_FAST_SCALED_FLOAT;
383 
384 // STB_VORBIS_MAX_CHANNELS [number]
385 //     globally define this to the maximum number of channels you need.
386 //     The spec does not put a restriction on channels except that
387 //     the count is stored in a byte, so 255 is the hard limit.
388 //     Reducing this saves about 16 bytes per value, so using 16 saves
389 //     (255-16)*16 or around 4KB. Plus anything other memory usage
390 //     I forgot to account for. Can probably go as low as 8 (7.1 audio),
391 //     6 (5.1 audio), or 2 (stereo only).
392 enum STB_VORBIS_MAX_CHANNELS = 16; // enough for anyone?
393 
394 // STB_VORBIS_PUSHDATA_CRC_COUNT [number]
395 //     after a flush_pushdata(), stb_vorbis begins scanning for the
396 //     next valid page, without backtracking. when it finds something
397 //     that looks like a page, it streams through it and verifies its
398 //     CRC32. Should that validation fail, it keeps scanning. But it's
399 //     possible that _while_ streaming through to check the CRC32 of
400 //     one candidate page, it sees another candidate page. This #define
401 //     determines how many "overlapping" candidate pages it can search
402 //     at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
403 //     garbage pages could be as big as 64KB, but probably average ~16KB.
404 //     So don't hose ourselves by scanning an apparent 64KB page and
405 //     missing a ton of real ones in the interim; so minimum of 2
406 enum STB_VORBIS_PUSHDATA_CRC_COUNT = 4;
407 
408 // STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
409 //     sets the log size of the huffman-acceleration table.  Maximum
410 //     supported value is 24. with larger numbers, more decodings are O(1),
411 //     but the table size is larger so worse cache missing, so you'll have
412 //     to probe (and try multiple ogg vorbis files) to find the sweet spot.
413 enum STB_VORBIS_FAST_HUFFMAN_LENGTH = 10;
414 
415 // STB_VORBIS_FAST_BINARY_LENGTH [number]
416 //     sets the log size of the binary-search acceleration table. this
417 //     is used in similar fashion to the fast-huffman size to set initial
418 //     parameters for the binary search
419 
420 // STB_VORBIS_FAST_HUFFMAN_INT
421 //     The fast huffman tables are much more efficient if they can be
422 //     stored as 16-bit results instead of 32-bit results. This restricts
423 //     the codebooks to having only 65535 possible outcomes, though.
424 //     (At least, accelerated by the huffman table.)
425 //version = STB_VORBIS_FAST_HUFFMAN_INT;
426 version(STB_VORBIS_FAST_HUFFMAN_INT) {} else version = STB_VORBIS_FAST_HUFFMAN_SHORT;
427 
428 // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
429 //     If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
430 //     back on binary searching for the correct one. This requires storing
431 //     extra tables with the huffman codes in sorted order. Defining this
432 //     symbol trades off space for speed by forcing a linear search in the
433 //     non-fast case, except for "sparse" codebooks.
434 //version = STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH;
435 
436 // STB_VORBIS_DIVIDES_IN_RESIDUE
437 //     stb_vorbis precomputes the result of the scalar residue decoding
438 //     that would otherwise require a divide per chunk. you can trade off
439 //     space for time by defining this symbol.
440 //version = STB_VORBIS_DIVIDES_IN_RESIDUE;
441 
442 // STB_VORBIS_DIVIDES_IN_CODEBOOK
443 //     vorbis VQ codebooks can be encoded two ways: with every case explicitly
444 //     stored, or with all elements being chosen from a small range of values,
445 //     and all values possible in all elements. By default, stb_vorbis expands
446 //     this latter kind out to look like the former kind for ease of decoding,
447 //     because otherwise an integer divide-per-vector-element is required to
448 //     unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
449 //     trade off storage for speed.
450 //version = STB_VORBIS_DIVIDES_IN_CODEBOOK;
451 
452 version(STB_VORBIS_CODEBOOK_SHORTS) static assert(
453     0,
454     "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
455 );
456 
457 // STB_VORBIS_DIVIDE_TABLE
458 //     this replaces small integer divides in the floor decode loop with
459 //     table lookups. made less than 1% difference, so disabled by default.
460 //version = STB_VORBIS_DIVIDE_TABLE;
461 
462 // STB_VORBIS_NO_DEFER_FLOOR
463 //     Normally we only decode the floor without synthesizing the actual
464 //     full curve. We can instead synthesize the curve immediately. This
465 //     requires more memory and is very likely slower, so I don't think
466 //     you'd ever want to do it except for debugging.
467 //version = STB_VORBIS_NO_DEFER_FLOOR;
468 //version(STB_VORBIS_CODEBOOK_FLOATS) static assert(0);
469 
470 
471 // ////////////////////////////////////////////////////////////////////////// //
472 private:
473 static assert(STB_VORBIS_MAX_CHANNELS <= 256, "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range");
474 static assert(STB_VORBIS_FAST_HUFFMAN_LENGTH <= 24, "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range");
475 
476 enum MAX_BLOCKSIZE_LOG = 13; // from specification
477 enum MAX_BLOCKSIZE = (1 << MAX_BLOCKSIZE_LOG);
478 
479 
480 alias codetype = float;
481 
482 // @NOTE
483 //
484 // Some arrays below are tagged "//varies", which means it's actually
485 // a variable-sized piece of data, but rather than malloc I assume it's
486 // small enough it's better to just allocate it all together with the
487 // main thing
488 //
489 // Most of the variables are specified with the smallest size I could pack
490 // them into. It might give better performance to make them all full-sized
491 // integers. It should be safe to freely rearrange the structures or change
492 // the sizes larger--nothing relies on silently truncating etc., nor the
493 // order of variables.
494 
495 enum FAST_HUFFMAN_TABLE_SIZE = (1<<STB_VORBIS_FAST_HUFFMAN_LENGTH);
496 enum FAST_HUFFMAN_TABLE_MASK = (FAST_HUFFMAN_TABLE_SIZE-1);
497 
498 struct Codebook {
499   int dimensions, entries;
500   ubyte* codeword_lengths;
501   float minimum_value;
502   float delta_value;
503   ubyte value_bits;
504   ubyte lookup_type;
505   ubyte sequence_p;
506   ubyte sparse;
507   uint lookup_values;
508   codetype* multiplicands;
509   uint *codewords;
510   version(STB_VORBIS_FAST_HUFFMAN_SHORT) {
511     short[FAST_HUFFMAN_TABLE_SIZE] fast_huffman;
512   } else {
513     int[FAST_HUFFMAN_TABLE_SIZE] fast_huffman;
514   }
515   uint* sorted_codewords;
516   int* sorted_values;
517   int sorted_entries;
518 }
519 
520 struct Floor0 {
521   ubyte order;
522   ushort rate;
523   ushort bark_map_size;
524   ubyte amplitude_bits;
525   ubyte amplitude_offset;
526   ubyte number_of_books;
527   ubyte[16] book_list; // varies
528 }
529 
530 struct Floor1 {
531   ubyte partitions;
532   ubyte[32] partition_class_list; // varies
533   ubyte[16] class_dimensions; // varies
534   ubyte[16] class_subclasses; // varies
535   ubyte[16] class_masterbooks; // varies
536   short[8][16] subclass_books; // varies
537   ushort[31*8+2] xList; // varies
538   ubyte[31*8+2] sorted_order;
539   ubyte[2][31*8+2] neighbors;
540   ubyte floor1_multiplier;
541   ubyte rangebits;
542   int values;
543 }
544 
545 union Floor {
546   Floor0 floor0;
547   Floor1 floor1;
548 }
549 
550 struct Residue {
551   uint begin, end;
552   uint part_size;
553   ubyte classifications;
554   ubyte classbook;
555   ubyte** classdata;
556   //int16 (*residue_books)[8];
557   short[8]* residue_books;
558 }
559 
560 struct MappingChannel {
561   ubyte magnitude;
562   ubyte angle;
563   ubyte mux;
564 }
565 
566 struct Mapping {
567   ushort coupling_steps;
568   MappingChannel* chan;
569   ubyte submaps;
570   ubyte[15] submap_floor; // varies
571   ubyte[15] submap_residue; // varies
572 }
573 
574 struct Mode {
575   ubyte blockflag;
576   ubyte mapping;
577   ushort windowtype;
578   ushort transformtype;
579 }
580 
581 struct CRCscan {
582   uint goal_crc;   // expected crc if match
583   int bytes_left;  // bytes left in packet
584   uint crc_so_far; // running crc
585   int bytes_done;  // bytes processed in _current_ chunk
586   uint sample_loc; // granule pos encoded in page
587 }
588 
589 struct ProbedPage {
590   uint page_start, page_end;
591   uint last_decoded_sample;
592 }
593 
594 int error (VorbisDecoder* f, STBVorbisError e) {
595   f.error = e;
596   if (!f.eof && e != STBVorbisError.need_more_data) {
597     f.error = e; // breakpoint for debugging
598   }
599   return 0;
600 }
601 
602 // these functions are used for allocating temporary memory
603 // while decoding. if you can afford the stack space, use
604 // alloca(); otherwise, provide a temp buffer and it will
605 // allocate out of those.
606 uint temp_alloc_save (VorbisDecoder* f) nothrow @nogc {
607     static if (__VERSION__ > 2067) pragma(inline, true);
608     return f.alloc.tempSave(f);
609 }
610 
611 void temp_alloc_restore (VorbisDecoder* f, uint p) nothrow @nogc {
612     static if (__VERSION__ > 2067) pragma(inline, true);
613     f.alloc.tempRestore(p, f);
614 
615 }
616 void temp_free (VorbisDecoder* f, void* p) nothrow @nogc {}
617 /*
618 T* temp_alloc(T) (VorbisDecoder* f, uint count) nothrow @nogc {
619   auto res = f.alloc.alloc(count*T.sizeof, f);
620   return cast(T*)res;
621 }
622 */
623 
624 /+
625 enum array_size_required(string count, string size) = q{((${count})*((void*).sizeof+(${size})))}.cmacroFixVars!("count", "size")(count, size);
626 
627 // has to be a mixin, due to `alloca`
628 template temp_alloc(string size) {
629   enum temp_alloc = q{(f.alloc.alloc_buffer ? setup_temp_malloc(f, (${size})) : alloca(${size}))}.cmacroFixVars!("size")(size);
630 }
631 
632 // has to be a mixin, due to `alloca`
633 template temp_block_array(string count, string size) {
634   enum temp_block_array = q{(make_block_array(${tam}, (${count}), (${size})))}
635     .cmacroFixVars!("count", "size", "tam")(count, size, temp_alloc!(array_size_required!(count, size)));
636 }
637 +/
638 enum array_size_required(string count, string size) = q{
639     ((${count})*((void*).sizeof+(${size})))
640 }.cmacroFixVars!("count", "size")(count, size);
641 
642 template temp_alloc(string size) {
643   enum temp_alloc = q{
644     alloca(${size})
645 }.cmacroFixVars!("size")(size);
646 }
647 
648 template temp_block_array(string count, string size) {
649   enum temp_block_array = q{(make_block_array(${tam}, (${count}), (${size})))}
650     .cmacroFixVars!("count", "size", "tam")(count, size, temp_alloc!(array_size_required!(count, size)));
651 }
652 
653 /*
654 T** temp_block_array(T) (VorbisDecoder* f, uint count, uint size) {
655   size *= T.sizeof;
656   auto mem = f.alloc.alloc(count*(void*).sizeof+size, f);
657   if (mem !is null) make_block_array(mem, count, size);
658   return cast(T**)mem;
659 }
660 */
661 
662 // given a sufficiently large block of memory, make an array of pointers to subblocks of it
663 void* make_block_array (void* mem, int count, int size) {
664   void** p = cast(void**)mem;
665   char* q = cast(char*)(p+count);
666   foreach (immutable i; 0..count) {
667     p[i] = q;
668     q += size;
669   }
670   return p;
671 }
672 
673 T* setup_malloc(T) (VorbisDecoder* f, uint sz) {
674   sz *= T.sizeof;
675   /*
676   f.setup_memory_required += sz;
677   if (f.alloc.alloc_buffer) {
678     void* p = cast(char*)f.alloc.alloc_buffer+f.setup_offset;
679     if (f.setup_offset+sz > f.temp_offset) return null;
680     f.setup_offset += sz;
681     return cast(T*)p;
682   }
683   */
684   auto res = f.alloc.alloc(sz+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
685   if (res !is null) {
686     import core.stdc.string : memset;
687     memset(res, 0, sz+8);
688   }
689   return cast(T*)res;
690 }
691 
692 void setup_free (VorbisDecoder* f, void* p) {
693   //if (f.alloc.alloc_buffer) return; // do nothing; setup mem is a stack
694   if (p !is null) f.alloc.free(p, f);
695 }
696 
697 void* setup_temp_malloc (VorbisDecoder* f, uint sz) {
698   auto res = f.alloc.allocTemp(sz+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
699   if (res !is null) {
700     import core.stdc.string : memset;
701     memset(res, 0, sz+8);
702   }
703   return res;
704 }
705 
706 void setup_temp_free (VorbisDecoder* f, void* p, uint sz) {
707   if (p !is null) f.alloc.freeTemp(p, (sz ? sz : 1)+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
708 }
709 
710 immutable uint[256] crc_table;
711 shared static this () {
712   enum CRC32_POLY = 0x04c11db7; // from spec
713   // init crc32 table
714   foreach (uint i; 0..256) {
715     uint s = i<<24;
716     foreach (immutable _; 0..8) s = (s<<1)^(s >= (1U<<31) ? CRC32_POLY : 0);
717     crc_table[i] = s;
718   }
719 }
720 
721 uint crc32_update (uint crc, ubyte b) {
722   static if (__VERSION__ > 2067) pragma(inline, true);
723   return (crc<<8)^crc_table[b^(crc>>24)];
724 }
725 
726 // used in setup, and for huffman that doesn't go fast path
727 uint bit_reverse (uint n) {
728   static if (__VERSION__ > 2067) pragma(inline, true);
729   n = ((n&0xAAAAAAAA)>>1)|((n&0x55555555)<<1);
730   n = ((n&0xCCCCCCCC)>>2)|((n&0x33333333)<<2);
731   n = ((n&0xF0F0F0F0)>>4)|((n&0x0F0F0F0F)<<4);
732   n = ((n&0xFF00FF00)>>8)|((n&0x00FF00FF)<<8);
733   return (n>>16)|(n<<16);
734 }
735 
736 float square (float x) {
737   static if (__VERSION__ > 2067) pragma(inline, true);
738   return x*x;
739 }
740 
741 // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
742 // as required by the specification. fast(?) implementation from stb.h
743 // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
744 immutable byte[16] log2_4 = [0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4];
745 int ilog (int n) {
746   //static if (__VERSION__ > 2067) pragma(inline, true);
747   if (n < 0) return 0; // signed n returns 0
748   // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
749   if (n < (1<<14)) {
750     if (n < (1<<4)) return 0+log2_4[n];
751     if (n < (1<<9)) return 5+log2_4[n>>5];
752     return 10+log2_4[n>>10];
753   } else if (n < (1<<24)) {
754     if (n < (1<<19)) return 15+log2_4[n>>15];
755     return 20+log2_4[n>>20];
756   } else {
757     if (n < (1<<29)) return 25+log2_4[n>>25];
758     return 30+log2_4[n>>30];
759   }
760 }
761 
762 
763 // code length assigned to a value with no huffman encoding
764 enum NO_CODE = 255;
765 
766 /////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
767 //
768 // these functions are only called at setup, and only a few times per file
769 float float32_unpack (uint x) {
770   import core.math : ldexp;
771   //static if (__VERSION__ > 2067) pragma(inline, true);
772   // from the specification
773   uint mantissa = x&0x1fffff;
774   uint sign = x&0x80000000;
775   uint exp = (x&0x7fe00000)>>21;
776   double res = (sign ? -cast(double)mantissa : cast(double)mantissa);
777   return cast(float)ldexp(cast(float)res, cast(int)exp-788);
778 }
779 
780 // zlib & jpeg huffman tables assume that the output symbols
781 // can either be arbitrarily arranged, or have monotonically
782 // increasing frequencies--they rely on the lengths being sorted;
783 // this makes for a very simple generation algorithm.
784 // vorbis allows a huffman table with non-sorted lengths. This
785 // requires a more sophisticated construction, since symbols in
786 // order do not map to huffman codes "in order".
787 void add_entry (Codebook* c, uint huff_code, int symbol, int count, ubyte len, uint* values) {
788   if (!c.sparse) {
789     c.codewords[symbol] = huff_code;
790   } else {
791     c.codewords[count] = huff_code;
792     c.codeword_lengths[count] = len;
793     values[count] = symbol;
794   }
795 }
796 
797 int compute_codewords (Codebook* c, ubyte* len, int n, uint* values) {
798   import core.stdc.string : memset;
799 
800   int i, k, m = 0;
801   uint[32] available;
802 
803   memset(available.ptr, 0, available.sizeof);
804   // find the first entry
805   for (k = 0; k < n; ++k) if (len[k] < NO_CODE) break;
806   if (k == n) { assert(c.sorted_entries == 0); return true; }
807   // add to the list
808   add_entry(c, 0, k, m++, len[k], values);
809   // add all available leaves
810   for (i = 1; i <= len[k]; ++i) available[i] = 1U<<(32-i);
811   // note that the above code treats the first case specially,
812   // but it's really the same as the following code, so they
813   // could probably be combined (except the initial code is 0,
814   // and I use 0 in available[] to mean 'empty')
815   for (i = k+1; i < n; ++i) {
816     uint res;
817     int z = len[i];
818     if (z == NO_CODE) continue;
819     // find lowest available leaf (should always be earliest,
820     // which is what the specification calls for)
821     // note that this property, and the fact we can never have
822     // more than one free leaf at a given level, isn't totally
823     // trivial to prove, but it seems true and the assert never
824     // fires, so!
825     while (z > 0 && !available[z]) --z;
826     if (z == 0) return false;
827     res = available[z];
828     assert(z >= 0 && z < 32);
829     available[z] = 0;
830     ubyte xxx = len[i];
831     add_entry(c,
832       bit_reverse(res),
833       i,
834       m++,
835       xxx, // dmd bug: it reads 4 bytes without temp
836       values);
837     // propogate availability up the tree
838     if (z != len[i]) {
839       assert(len[i] >= 0 && len[i] < 32);
840       for (int y = len[i]; y > z; --y) {
841         assert(available[y] == 0);
842         available[y] = res+(1<<(32-y));
843       }
844     }
845   }
846   return true;
847 }
848 
849 // accelerated huffman table allows fast O(1) match of all symbols
850 // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
851 void compute_accelerated_huffman (Codebook* c) {
852   //for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c.fast_huffman.ptr[i] = -1;
853   c.fast_huffman.ptr[0..FAST_HUFFMAN_TABLE_SIZE] = -1;
854   auto len = (c.sparse ? c.sorted_entries : c.entries);
855   version(STB_VORBIS_FAST_HUFFMAN_SHORT) {
856     if (len > 32_767) len = 32_767; // largest possible value we can encode!
857   }
858   foreach (uint i; 0..len) {
859     if (c.codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
860       uint z = (c.sparse ? bit_reverse(c.sorted_codewords[i]) : c.codewords[i]);
861       // set table entries for all bit combinations in the higher bits
862       while (z < FAST_HUFFMAN_TABLE_SIZE) {
863         c.fast_huffman.ptr[z] = cast(typeof(c.fast_huffman[0]))i; //k8
864         z += 1<<c.codeword_lengths[i];
865       }
866     }
867   }
868 }
869 
870 extern(C) int uint32_compare (const void* p, const void* q) {
871   uint x = *cast(uint*)p;
872   uint y = *cast(uint*)q;
873   return (x < y ? -1 : x > y);
874 }
875 
876 int include_in_sort (Codebook* c, uint len) {
877   if (c.sparse) { assert(len != NO_CODE); return true; }
878   if (len == NO_CODE) return false;
879   if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return true;
880   return false;
881 }
882 
883 // if the fast table above doesn't work, we want to binary
884 // search them... need to reverse the bits
885 void compute_sorted_huffman (Codebook* c, ubyte* lengths, uint* values) {
886   // build a list of all the entries
887   // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
888   // this is kind of a frivolous optimization--I don't see any performance improvement,
889   // but it's like 4 extra lines of code, so.
890   if (!c.sparse) {
891     int k = 0;
892     foreach (uint i; 0..c.entries)
893         if (include_in_sort(c, lengths[i])) c.sorted_codewords[k++] = bit_reverse(c.codewords[i]);
894     assert(k == c.sorted_entries);
895   } else {
896         foreach (uint i; 0..c.sorted_entries)
897             c.sorted_codewords[i] = bit_reverse(c.codewords[i]);
898   }
899 
900   qsort(c.sorted_codewords, c.sorted_entries, (c.sorted_codewords[0]).sizeof, &uint32_compare);
901   c.sorted_codewords[c.sorted_entries] = 0xffffffff;
902 
903   auto len = (c.sparse ? c.sorted_entries : c.entries);
904   // now we need to indicate how they correspond; we could either
905   //   #1: sort a different data structure that says who they correspond to
906   //   #2: for each sorted entry, search the original list to find who corresponds
907   //   #3: for each original entry, find the sorted entry
908   // #1 requires extra storage, #2 is slow, #3 can use binary search!
909   foreach (uint i; 0..len) {
910     auto huff_len = (c.sparse ? lengths[values[i]] : lengths[i]);
911     if (include_in_sort(c, huff_len)) {
912       uint code = bit_reverse(c.codewords[i]);
913       int x = 0, n = c.sorted_entries;
914       while (n > 1) {
915         // invariant: sc[x] <= code < sc[x+n]
916         int m = x+(n>>1);
917         if (c.sorted_codewords[m] <= code) {
918           x = m;
919           n -= (n>>1);
920         } else {
921           n >>= 1;
922         }
923       }
924       assert(c.sorted_codewords[x] == code);
925       if (c.sparse) {
926         c.sorted_values[x] = values[i];
927         c.codeword_lengths[x] = huff_len;
928       } else {
929         c.sorted_values[x] = i;
930       }
931     }
932   }
933 }
934 
935 // only run while parsing the header (3 times)
936 int vorbis_validate (const(void)* data) {
937   static if (__VERSION__ > 2067) pragma(inline, true);
938   immutable char[6] vorbis = "vorbis";
939   return ((cast(char*)data)[0..6] == vorbis[]);
940 }
941 
942 // called from setup only, once per code book
943 // (formula implied by specification)
944 int lookup1_values (int entries, int dim) {
945   import core.stdc.math : lrintf;
946   import std.math : floor, exp, pow, log;
947   int r = cast(int)lrintf(floor(exp(cast(float)log(cast(float)entries)/dim)));
948   if (lrintf(floor(pow(cast(float)r+1, dim))) <= entries) ++r; // (int) cast for MinGW warning; floor() to avoid _ftol() when non-CRT
949   assert(pow(cast(float)r+1, dim) > entries);
950   assert(lrintf(floor(pow(cast(float)r, dim))) <= entries); // (int), floor() as above
951   return r;
952 }
953 
954 // called twice per file
955 void compute_twiddle_factors (int n, float* A, float* B, float* C) {
956   import std.math : cos, sin, PI;
957   int n4 = n>>2, n8 = n>>3;
958   int k, k2;
959   for (k = k2 = 0; k < n4; ++k, k2 += 2) {
960     A[k2  ] = cast(float) cos(4*k*PI/n);
961     A[k2+1] = cast(float)-sin(4*k*PI/n);
962     B[k2  ] = cast(float) cos((k2+1)*PI/n/2)*0.5f;
963     B[k2+1] = cast(float) sin((k2+1)*PI/n/2)*0.5f;
964   }
965   for (k = k2 = 0; k < n8; ++k, k2 += 2) {
966     C[k2  ] = cast(float) cos(2*(k2+1)*PI/n);
967     C[k2+1] = cast(float)-sin(2*(k2+1)*PI/n);
968   }
969 }
970 
971 void compute_window (int n, float* window) {
972   import std.math : sin, PI;
973   int n2 = n>>1;
974   foreach (int i; 0..n2) *window++ = cast(float)sin(0.5*PI*square(cast(float)sin((i-0+0.5)/n2*0.5*PI)));
975 }
976 
977 void compute_bitreverse (int n, ushort* rev) {
978   int ld = ilog(n)-1; // ilog is off-by-one from normal definitions
979   int n8 = n>>3;
980   foreach (int i; 0..n8) *rev++ = cast(ushort)((bit_reverse(i)>>(32-ld+3))<<2); //k8
981 }
982 
983 int init_blocksize (VorbisDecoder* f, int b, int n) {
984   int n2 = n>>1, n4 = n>>2, n8 = n>>3;
985   f.A[b] = setup_malloc!float(f, n2);
986   f.B[b] = setup_malloc!float(f, n2);
987   f.C[b] = setup_malloc!float(f, n4);
988   if (f.A[b] is null || f.B[b] is null || f.C[b] is null) return error(f, STBVorbisError.outofmem);
989   compute_twiddle_factors(n, f.A[b], f.B[b], f.C[b]);
990   f.window[b] = setup_malloc!float(f, n2);
991   if (f.window[b] is null) return error(f, STBVorbisError.outofmem);
992   compute_window(n, f.window[b]);
993   f.bit_reverse[b] = setup_malloc!ushort(f, n8);
994   if (f.bit_reverse[b] is null) return error(f, STBVorbisError.outofmem);
995   compute_bitreverse(n, f.bit_reverse[b]);
996   return true;
997 }
998 
999 void neighbors (ushort* x, int n, ushort* plow, ushort* phigh) {
1000   int low = -1;
1001   int high = 65_536;
1002   assert(n >= 0 && n <= ushort.max);
1003   foreach (ushort i; 0..cast(ushort)n) {
1004     if (x[i] > low  && x[i] < x[n]) { *plow = i; low = x[i]; }
1005     if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
1006   }
1007 }
1008 
1009 // this has been repurposed so y is now the original index instead of y
1010 struct Point {
1011   ushort x, y;
1012 }
1013 
1014 extern(C) int point_compare (const void *p, const void *q) {
1015   auto a = cast(const(Point)*)p;
1016   auto b = cast(const(Point)*)q;
1017   return (a.x < b.x ? -1 : a.x > b.x);
1018 }
1019 /////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
1020 
1021 // ///////////////////////////////////////////////////////////////////// //
1022 ubyte get8 (VorbisDecoder* f) {
1023   ubyte b = void;
1024   if (!f.eof) {
1025     if (f.rawRead((&b)[0..1]) != 1) { f.eof = true; b = 0; }
1026   }
1027   return b;
1028 }
1029 
1030 uint get32 (VorbisDecoder* f) {
1031   uint x = 0;
1032   if (!f.eof) {
1033     version(LittleEndian) {
1034       if (f.rawRead((&x)[0..1]) != x.sizeof) { f.eof = true; x = 0; }
1035     } else {
1036       x = get8(f);
1037       x |= cast(uint)get8(f)<<8;
1038       x |= cast(uint)get8(f)<<16;
1039       x |= cast(uint)get8(f)<<24;
1040     }
1041   }
1042   return x;
1043 }
1044 
1045 bool getn (VorbisDecoder* f, void* data, int n) {
1046   if (f.eof || n < 0) return false;
1047   if (n == 0) return true;
1048   if (f.rawRead(data[0..n]) != n) { f.eof = true; return false; }
1049   return true;
1050 }
1051 
1052 void skip (VorbisDecoder* f, int n) {
1053   if (f.eof || n <= 0) return;
1054   f.rawSkip(n);
1055 }
1056 
1057 void set_file_offset (VorbisDecoder* f, uint loc) {
1058   /+if (f.push_mode) return;+/
1059   f.eof = false;
1060   if (loc >= 0x80000000) { f.eof = true; return; }
1061   f.rawSeek(loc);
1062 }
1063 
1064 
1065 immutable char[4] ogg_page_header = "OggS"; //[ 0x4f, 0x67, 0x67, 0x53 ];
1066 
1067 bool capture_pattern (VorbisDecoder* f) {
1068   static if (__VERSION__ > 2067) pragma(inline, true);
1069   char[4] sign = void;
1070   if (!getn(f, sign.ptr, 4)) return false;
1071   return (sign == "OggS");
1072 }
1073 
1074 enum PAGEFLAG_continued_packet = 1;
1075 enum PAGEFLAG_first_page = 2;
1076 enum PAGEFLAG_last_page = 4;
1077 
1078 int start_page_no_capturepattern (VorbisDecoder* f) {
1079   uint loc0, loc1, n;
1080   // stream structure version
1081   if (get8(f) != 0) return error(f, STBVorbisError.invalid_stream_structure_version);
1082   // header flag
1083   f.page_flag = get8(f);
1084   // absolute granule position
1085   loc0 = get32(f);
1086   loc1 = get32(f);
1087 
1088   // This is put here to turn off IDE warnings
1089   uint discardConsumer;
1090   // @TODO: validate loc0, loc1 as valid positions?
1091   // stream serial number -- vorbis doesn't interleave, so discard
1092   discardConsumer = get32(f);
1093   //if (f.serial != get32(f)) return error(f, STBVorbisError.incorrect_stream_serial_number);
1094   // page sequence number
1095   n = get32(f);
1096   f.last_page = n;
1097   // CRC32
1098   discardConsumer = get32(f);
1099   // page_segments
1100   f.segment_count = get8(f);
1101   if (!getn(f, f.segments.ptr, f.segment_count)) return error(f, STBVorbisError.unexpected_eof);
1102   // assume we _don't_ know any the sample position of any segments
1103   f.end_seg_with_known_loc = -2;
1104   if (loc0 != ~0U || loc1 != ~0U) {
1105     int i;
1106     // determine which packet is the last one that will complete
1107     for (i = f.segment_count-1; i >= 0; --i) if (f.segments.ptr[i] < 255) break;
1108     // 'i' is now the index of the _last_ segment of a packet that ends
1109     if (i >= 0) {
1110       f.end_seg_with_known_loc = i;
1111       f.known_loc_for_packet = loc0;
1112     }
1113   }
1114   if (f.first_decode) {
1115     int len;
1116     ProbedPage p;
1117     len = 0;
1118     foreach (int i; 0..f.segment_count) len += f.segments.ptr[i];
1119     len += 27+f.segment_count;
1120     p.page_start = f.first_audio_page_offset;
1121     p.page_end = p.page_start+len;
1122     p.last_decoded_sample = loc0;
1123     f.p_first = p;
1124   }
1125   f.next_seg = 0;
1126   return true;
1127 }
1128 
1129 int start_page (VorbisDecoder* f) {
1130   if (!capture_pattern(f)) return error(f, STBVorbisError.missing_capture_pattern);
1131   return start_page_no_capturepattern(f);
1132 }
1133 
1134 int start_packet (VorbisDecoder* f) {
1135   while (f.next_seg == -1) {
1136     if (!start_page(f)) return false;
1137     if (f.page_flag&PAGEFLAG_continued_packet) return error(f, STBVorbisError.continued_packet_flag_invalid);
1138   }
1139   f.last_seg = false;
1140   f.valid_bits = 0;
1141   f.packet_bytes = 0;
1142   f.bytes_in_seg = 0;
1143   // f.next_seg is now valid
1144   return true;
1145 }
1146 
1147 int maybe_start_packet (VorbisDecoder* f) {
1148   if (f.next_seg == -1) {
1149     auto x = get8(f);
1150     if (f.eof) return false; // EOF at page boundary is not an error!
1151     if (0x4f != x      ) return error(f, STBVorbisError.missing_capture_pattern);
1152     if (0x67 != get8(f)) return error(f, STBVorbisError.missing_capture_pattern);
1153     if (0x67 != get8(f)) return error(f, STBVorbisError.missing_capture_pattern);
1154     if (0x53 != get8(f)) return error(f, STBVorbisError.missing_capture_pattern);
1155     if (!start_page_no_capturepattern(f)) return false;
1156     if (f.page_flag&PAGEFLAG_continued_packet) {
1157       // set up enough state that we can read this packet if we want,
1158       // e.g. during recovery
1159       f.last_seg = false;
1160       f.bytes_in_seg = 0;
1161       return error(f, STBVorbisError.continued_packet_flag_invalid);
1162     }
1163   }
1164   return start_packet(f);
1165 }
1166 
1167 int next_segment (VorbisDecoder* f) {
1168   if (f.last_seg) return 0;
1169   if (f.next_seg == -1) {
1170     f.last_seg_which = f.segment_count-1; // in case start_page fails
1171     if (!start_page(f)) { f.last_seg = 1; return 0; }
1172     if (!(f.page_flag&PAGEFLAG_continued_packet)) return error(f, STBVorbisError.continued_packet_flag_invalid);
1173   }
1174   auto len = f.segments.ptr[f.next_seg++];
1175   if (len < 255) {
1176     f.last_seg = true;
1177     f.last_seg_which = f.next_seg-1;
1178   }
1179   if (f.next_seg >= f.segment_count) f.next_seg = -1;
1180   debug(stb_vorbis) assert(f.bytes_in_seg == 0);
1181   f.bytes_in_seg = len;
1182   return len;
1183 }
1184 
1185 enum EOP = (-1);
1186 enum INVALID_BITS = (-1);
1187 
1188 int get8_packet_raw (VorbisDecoder* f) {
1189   if (!f.bytes_in_seg) {  // CLANG!
1190     if (f.last_seg) return EOP;
1191     else if (!next_segment(f)) return EOP;
1192   }
1193   debug(stb_vorbis) assert(f.bytes_in_seg > 0);
1194   --f.bytes_in_seg;
1195   ++f.packet_bytes;
1196   return get8(f);
1197 }
1198 
1199 int get8_packet (VorbisDecoder* f) {
1200   int x = get8_packet_raw(f);
1201   f.valid_bits = 0;
1202   return x;
1203 }
1204 
1205 uint get32_packet (VorbisDecoder* f) {
1206   uint x = get8_packet(f), b;
1207   if (x == EOP) return EOP;
1208   if ((b = get8_packet(f)) == EOP) return EOP;
1209   x += b<<8;
1210   if ((b = get8_packet(f)) == EOP) return EOP;
1211   x += b<<16;
1212   if ((b = get8_packet(f)) == EOP) return EOP;
1213   x += b<<24;
1214   return x;
1215 }
1216 
1217 void flush_packet (VorbisDecoder* f) {
1218   while (get8_packet_raw(f) != EOP) {}
1219 }
1220 
1221 // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
1222 // as the huffman decoder?
1223 uint get_bits_main (VorbisDecoder* f, int n) {
1224   uint z;
1225   if (f.valid_bits < 0) return 0;
1226   if (f.valid_bits < n) {
1227     if (n > 24) {
1228       // the accumulator technique below would not work correctly in this case
1229       z = get_bits_main(f, 24);
1230       z += get_bits_main(f, n-24)<<24;
1231       return z;
1232     }
1233     if (f.valid_bits == 0) f.acc = 0;
1234     while (f.valid_bits < n) {
1235       z = get8_packet_raw(f);
1236       if (z == EOP) {
1237         f.valid_bits = INVALID_BITS;
1238         return 0;
1239       }
1240       f.acc += z<<f.valid_bits;
1241       f.valid_bits += 8;
1242     }
1243   }
1244   if (f.valid_bits < 0) return 0;
1245   z = f.acc&((1<<n)-1);
1246   f.acc >>= n;
1247   f.valid_bits -= n;
1248   return z;
1249 }
1250 
1251 // chooses minimal possible integer type
1252 auto get_bits(ubyte n) (VorbisDecoder* f) if (n >= 1 && n <= 64) {
1253   static if (n <= 8) return cast(ubyte)get_bits_main(f, n);
1254   else static if (n <= 16) return cast(ushort)get_bits_main(f, n);
1255   else static if (n <= 32) return cast(uint)get_bits_main(f, n);
1256   else static if (n <= 64) return cast(ulong)get_bits_main(f, n);
1257   else static assert(0, "wtf?!");
1258 }
1259 
1260 // chooses minimal possible integer type, assume no overflow
1261 auto get_bits_add_no(ubyte n) (VorbisDecoder* f, ubyte add) if (n >= 1 && n <= 64) {
1262   static if (n <= 8) return cast(ubyte)(get_bits_main(f, n)+add);
1263   else static if (n <= 16) return cast(ushort)(get_bits_main(f, n)+add);
1264   else static if (n <= 32) return cast(uint)(get_bits_main(f, n)+add);
1265   else static if (n <= 64) return cast(ulong)(get_bits_main(f, n)+add);
1266   else static assert(0, "wtf?!");
1267 }
1268 
1269 // @OPTIMIZE: primary accumulator for huffman
1270 // expand the buffer to as many bits as possible without reading off end of packet
1271 // it might be nice to allow f.valid_bits and f.acc to be stored in registers,
1272 // e.g. cache them locally and decode locally
1273 ///*__forceinline*/ void prep_huffman (VorbisDecoder* f)
1274 enum PrepHuffmanMixin = q{
1275   if (f.valid_bits <= 24) {
1276     if (f.valid_bits == 0) f.acc = 0;
1277     int phmz = void;
1278     do {
1279       if (f.last_seg && !f.bytes_in_seg) break;
1280       phmz = get8_packet_raw(f);
1281       if (phmz == EOP) break;
1282       f.acc += cast(uint)phmz<<f.valid_bits;
1283       f.valid_bits += 8;
1284     } while (f.valid_bits <= 24);
1285   }
1286 };
1287 
1288 enum VorbisPacket {
1289   id = 1,
1290   comment = 3,
1291   setup = 5,
1292 }
1293 
1294 int codebook_decode_scalar_raw (VorbisDecoder* f, Codebook *c) {
1295   mixin(PrepHuffmanMixin);
1296 
1297   if (c.codewords is null && c.sorted_codewords is null) return -1;
1298   // cases to use binary search: sorted_codewords && !c.codewords
1299   //                             sorted_codewords && c.entries > 8
1300   auto cond = (c.entries > 8 ? c.sorted_codewords !is null : !c.codewords);
1301   if (cond) {
1302     // binary search
1303     uint code = bit_reverse(f.acc);
1304     int x = 0, n = c.sorted_entries, len;
1305     while (n > 1) {
1306       // invariant: sc[x] <= code < sc[x+n]
1307       int m = x+(n>>1);
1308       if (c.sorted_codewords[m] <= code) {
1309         x = m;
1310         n -= (n>>1);
1311       } else {
1312         n >>= 1;
1313       }
1314     }
1315     // x is now the sorted index
1316     if (!c.sparse) x = c.sorted_values[x];
1317     // x is now sorted index if sparse, or symbol otherwise
1318     len = c.codeword_lengths[x];
1319     if (f.valid_bits >= len) {
1320       f.acc >>= len;
1321       f.valid_bits -= len;
1322       return x;
1323     }
1324     f.valid_bits = 0;
1325     return -1;
1326   }
1327   // if small, linear search
1328   debug(stb_vorbis) assert(!c.sparse);
1329   foreach (uint i; 0..c.entries) {
1330     if (c.codeword_lengths[i] == NO_CODE) continue;
1331     if (c.codewords[i] == (f.acc&((1<<c.codeword_lengths[i])-1))) {
1332       if (f.valid_bits >= c.codeword_lengths[i]) {
1333         f.acc >>= c.codeword_lengths[i];
1334         f.valid_bits -= c.codeword_lengths[i];
1335         return i;
1336       }
1337       f.valid_bits = 0;
1338       return -1;
1339     }
1340   }
1341   
1342   // This is put here as a way to turn off IDE warnings
1343   uint discardConsumer;
1344   discardConsumer = error(f, STBVorbisError.invalid_stream);
1345   f.valid_bits = 0;
1346   return -1;
1347 }
1348 
1349 
1350 template DECODE_RAW(string var, string c) {
1351   enum DECODE_RAW = q{
1352     if (f.valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) { mixin(PrepHuffmanMixin); }
1353     // fast huffman table lookup
1354     ${i} = f.acc&FAST_HUFFMAN_TABLE_MASK;
1355     ${i} = ${c}.fast_huffman.ptr[${i}];
1356     if (${i} >= 0) {
1357       auto ${__temp_prefix__}n = ${c}.codeword_lengths[${i}];
1358       f.acc >>= ${__temp_prefix__}n;
1359       f.valid_bits -= ${__temp_prefix__}n;
1360       if (f.valid_bits < 0) { f.valid_bits = 0; ${i} = -1; }
1361     } else {
1362       ${i} = codebook_decode_scalar_raw(f, ${c});
1363     }
1364   }.cmacroFixVars!("i", "c")(var, c);
1365 }
1366 
1367 enum DECODE(string var, string c) = q{
1368   ${DECODE_RAW}
1369   if (${c}.sparse) ${var} = ${c}.sorted_values[${var}];
1370 }.cmacroFixVars!("var", "c", "DECODE_RAW")(var, c, DECODE_RAW!(var, c));
1371 
1372 
1373 version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {
1374   alias DECODE_VQ = DECODE;
1375 } else {
1376   alias DECODE_VQ = DECODE_RAW;
1377 }
1378 
1379 
1380 
1381 // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
1382 // where we avoid one addition
1383 enum CODEBOOK_ELEMENT(string c, string off) = "("~c~".multiplicands["~off~"])";
1384 enum CODEBOOK_ELEMENT_FAST(string c, string off) = "("~c~".multiplicands["~off~"])";
1385 enum CODEBOOK_ELEMENT_BASE(string c) = "(0)";
1386 
1387 
1388 int codebook_decode_start (VorbisDecoder* f, Codebook* c) {
1389   int z = -1;
1390   // type 0 is only legal in a scalar context
1391   if (c.lookup_type == 0) {
1392     // This is put here as a way to turn off IDE warnings
1393     uint discardConsumer;
1394     discardConsumer = error(f, STBVorbisError.invalid_stream);
1395   } else {
1396     mixin(DECODE_VQ!("z", "c"));
1397     debug(stb_vorbis) if (c.sparse) assert(z < c.sorted_entries);
1398     if (z < 0) {  // check for EOP
1399       if (!f.bytes_in_seg && f.last_seg) return z;
1400       // This is put here as a way to turn off IDE warnings
1401       uint discardConsumer;
1402       discardConsumer = error(f, STBVorbisError.invalid_stream);
1403     }
1404   }
1405   return z;
1406 }
1407 
1408 int codebook_decode (VorbisDecoder* f, Codebook* c, float* output, int len) {
1409   int z = codebook_decode_start(f, c);
1410   if (z < 0) return false;
1411   if (len > c.dimensions) len = c.dimensions;
1412 
1413   version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {
1414     if (c.lookup_type == 1) {
1415       float last = mixin(CODEBOOK_ELEMENT_BASE!"c");
1416       int div = 1;
1417       foreach (immutable i; 0..len) {
1418         int off = (z/div)%c.lookup_values;
1419         float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "off"))+last;
1420         output[i] += val;
1421         if (c.sequence_p) last = val+c.minimum_value;
1422         div *= c.lookup_values;
1423       }
1424       return true;
1425     }
1426   }
1427 
1428   z *= c.dimensions;
1429   if (c.sequence_p) {
1430     float last = mixin(CODEBOOK_ELEMENT_BASE!"c");
1431     foreach (immutable i; 0..len) {
1432       float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "z+i"))+last;
1433       output[i] += val;
1434       last = val+c.minimum_value;
1435     }
1436   } else {
1437     float last = mixin(CODEBOOK_ELEMENT_BASE!"c");
1438     foreach (immutable i; 0..len) output[i] += mixin(CODEBOOK_ELEMENT_FAST!("c", "z+i"))+last;
1439   }
1440 
1441   return true;
1442 }
1443 
1444 int codebook_decode_step (VorbisDecoder* f, Codebook* c, float* output, int len, int step) {
1445   int z = codebook_decode_start(f, c);
1446   float last = mixin(CODEBOOK_ELEMENT_BASE!"c");
1447   if (z < 0) return false;
1448   if (len > c.dimensions) len = c.dimensions;
1449 
1450   version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {
1451     if (c.lookup_type == 1) {
1452       int div = 1;
1453       foreach (immutable i; 0..len) {
1454         int off = (z/div)%c.lookup_values;
1455         float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "off"))+last;
1456         output[i*step] += val;
1457         if (c.sequence_p) last = val;
1458         div *= c.lookup_values;
1459       }
1460       return true;
1461     }
1462   }
1463 
1464   z *= c.dimensions;
1465   foreach (immutable i; 0..len) {
1466     float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "z+i"))+last;
1467     output[i*step] += val;
1468     if (c.sequence_p) last = val;
1469   }
1470 
1471   return true;
1472 }
1473 
1474 int codebook_decode_deinterleave_repeat (
1475 VorbisDecoder* f, 
1476 Codebook* c, 
1477 ref float*[STB_VORBIS_MAX_CHANNELS] outputs, 
1478 int ch, int* c_inter_p, 
1479 int* p_inter_p, int len, 
1480 int total_decode) {
1481   
1482   int c_inter = *c_inter_p;
1483   int p_inter = *p_inter_p;
1484   int z, effective = c.dimensions;
1485 
1486   // type 0 is only legal in a scalar context
1487   if (c.lookup_type == 0) return error(f, STBVorbisError.invalid_stream);
1488 
1489   while (total_decode > 0) {
1490     float last = mixin(CODEBOOK_ELEMENT_BASE!"c");
1491     mixin(DECODE_VQ!("z", "c"));
1492     version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {} else {
1493       debug(stb_vorbis) assert(!c.sparse || z < c.sorted_entries);
1494     }
1495     if (z < 0) {
1496       if (!f.bytes_in_seg && f.last_seg) return false;
1497       return error(f, STBVorbisError.invalid_stream);
1498     }
1499 
1500     // if this will take us off the end of the buffers, stop short!
1501     // we check by computing the length of the virtual interleaved
1502     // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
1503     // and the length we'll be using (effective)
1504     if (c_inter+p_inter*ch+effective > len*ch) effective = len*ch-(p_inter*ch-c_inter);
1505 
1506     version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {
1507       if (c.lookup_type == 1) {
1508         int div = 1;
1509         foreach (immutable i; 0..effective) {
1510           int off = (z/div)%c.lookup_values;
1511           float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "off"))+last;
1512           if (outputs.ptr[c_inter]) outputs.ptr[c_inter].ptr[p_inter] += val;
1513           if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1514           if (c.sequence_p) last = val;
1515           div *= c.lookup_values;
1516         }
1517         goto skipit;
1518       }
1519     }
1520     z *= c.dimensions;
1521     if (c.sequence_p) {
1522       foreach (immutable i; 0..effective) {
1523         float val = mixin(CODEBOOK_ELEMENT_FAST!("c", "z+i"))+last;
1524         if (outputs.ptr[c_inter]) outputs.ptr[c_inter][p_inter] += val;
1525         if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1526         last = val;
1527       }
1528     } else {
1529       foreach (immutable i; 0..effective) {
1530         float val = mixin(CODEBOOK_ELEMENT_FAST!("c","z+i"))+last;
1531         if (outputs.ptr[c_inter]) outputs.ptr[c_inter][p_inter] += val;
1532         if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1533       }
1534     }
1535    skipit:
1536     total_decode -= effective;
1537   }
1538   *c_inter_p = c_inter;
1539   *p_inter_p = p_inter;
1540   return true;
1541 }
1542 
1543 //int predict_point (int x, int x0, int x1, int y0, int y1)
1544 enum predict_point(string dest, string x, string x0, string x1, string y0, string y1) = q{{
1545   //import std.math : abs;
1546   int dy = ${y1}-${y0};
1547   int adx = ${x1}-${x0};
1548   // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
1549   int err = /*abs(dy)*/(dy < 0 ? -dy : dy)*(${x}-${x0});
1550   int off = err/adx;
1551   /*return*/${dest} = (dy < 0 ? ${y0}-off : ${y0}+off);
1552 }}.cmacroFixVars!("dest", "x", "x0", "x1", "y0", "y1")(dest, x, x0, x1, y0, y1);
1553 
1554 // the following table is block-copied from the specification
1555 immutable float[256] inverse_db_table = [
1556   1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1557   1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1558   1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
1559   2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
1560   2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
1561   3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
1562   4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
1563   6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
1564   7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1565   1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1566   1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1567   1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
1568   2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
1569   2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
1570   3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
1571   4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
1572   5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
1573   7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
1574   9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1575   1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1576   1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
1577   2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
1578   2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
1579   3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
1580   4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
1581   5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
1582   7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
1583   9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
1584   0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
1585   0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
1586   0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
1587   0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
1588   0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
1589   0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
1590   0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
1591   0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
1592   0.00092223983f, 0.00098217216f, 0.0010459992f,  0.0011139742f,
1593   0.0011863665f,  0.0012634633f,  0.0013455702f,  0.0014330129f,
1594   0.0015261382f,  0.0016253153f,  0.0017309374f,  0.0018434235f,
1595   0.0019632195f,  0.0020908006f,  0.0022266726f,  0.0023713743f,
1596   0.0025254795f,  0.0026895994f,  0.0028643847f,  0.0030505286f,
1597   0.0032487691f,  0.0034598925f,  0.0036847358f,  0.0039241906f,
1598   0.0041792066f,  0.0044507950f,  0.0047400328f,  0.0050480668f,
1599   0.0053761186f,  0.0057254891f,  0.0060975636f,  0.0064938176f,
1600   0.0069158225f,  0.0073652516f,  0.0078438871f,  0.0083536271f,
1601   0.0088964928f,  0.009474637f,   0.010090352f,   0.010746080f,
1602   0.011444421f,   0.012188144f,   0.012980198f,   0.013823725f,
1603   0.014722068f,   0.015678791f,   0.016697687f,   0.017782797f,
1604   0.018938423f,   0.020169149f,   0.021479854f,   0.022875735f,
1605   0.024362330f,   0.025945531f,   0.027631618f,   0.029427276f,
1606   0.031339626f,   0.033376252f,   0.035545228f,   0.037855157f,
1607   0.040315199f,   0.042935108f,   0.045725273f,   0.048696758f,
1608   0.051861348f,   0.055231591f,   0.058820850f,   0.062643361f,
1609   0.066714279f,   0.071049749f,   0.075666962f,   0.080584227f,
1610   0.085821044f,   0.091398179f,   0.097337747f,   0.10366330f,
1611   0.11039993f,    0.11757434f,    0.12521498f,    0.13335215f,
1612   0.14201813f,    0.15124727f,    0.16107617f,    0.17154380f,
1613   0.18269168f,    0.19456402f,    0.20720788f,    0.22067342f,
1614   0.23501402f,    0.25028656f,    0.26655159f,    0.28387361f,
1615   0.30232132f,    0.32196786f,    0.34289114f,    0.36517414f,
1616   0.38890521f,    0.41417847f,    0.44109412f,    0.46975890f,
1617   0.50028648f,    0.53279791f,    0.56742212f,    0.60429640f,
1618   0.64356699f,    0.68538959f,    0.72993007f,    0.77736504f,
1619   0.82788260f,    0.88168307f,    0.9389798f,     1.0f
1620 ];
1621 
1622 
1623 // @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
1624 // note that you must produce bit-identical output to decode correctly;
1625 // this specific sequence of operations is specified in the spec (it's
1626 // drawing integer-quantized frequency-space lines that the encoder
1627 // expects to be exactly the same)
1628 //     ... also, isn't the whole point of Bresenham's algorithm to NOT
1629 // have to divide in the setup? sigh.
1630 version(STB_VORBIS_NO_DEFER_FLOOR) {
1631   enum LINE_OP(string a, string b) = a~" = "~b~";";
1632 } else {
1633   enum LINE_OP(string a, string b) = a~" *= "~b~";";
1634 }
1635 
1636 version(STB_VORBIS_DIVIDE_TABLE) {
1637   enum DIVTAB_NUMER = 32;
1638   enum DIVTAB_DENOM = 64;
1639   byte[DIVTAB_DENOM][DIVTAB_NUMER] integer_divide_table; // 2KB
1640 }
1641 
1642 // nobranch abs trick
1643 enum ABS(string v) = q{(((${v})+((${v})>>31))^((${v})>>31))}.cmacroFixVars!"v"(v);
1644 
1645 // this is forceinline, but dmd inliner sux
1646 // but hey, i have my k00l macrosystem!
1647 //void draw_line (float* ${output}, int ${x0}, int ${y0}, int ${x1}, int ${y1}, int ${n})
1648 enum draw_line(string output, string x0, string y0, string x1, string y1, string n) = q{{
1649   int ${__temp_prefix__}dy = ${y1}-${y0};
1650   int ${__temp_prefix__}adx = ${x1}-${x0};
1651   int ${__temp_prefix__}ady = mixin(ABS!"${__temp_prefix__}dy");
1652   int ${__temp_prefix__}base;
1653   int ${__temp_prefix__}x = ${x0}, ${__temp_prefix__}y = ${y0};
1654   int ${__temp_prefix__}err = 0;
1655   int ${__temp_prefix__}sy;
1656 
1657   version(STB_VORBIS_DIVIDE_TABLE) {
1658     if (${__temp_prefix__}adx < DIVTAB_DENOM && ${__temp_prefix__}ady < DIVTAB_NUMER) {
1659       if (${__temp_prefix__}dy < 0) {
1660         ${__temp_prefix__}base = -integer_divide_table[${__temp_prefix__}ady].ptr[${__temp_prefix__}adx];
1661         ${__temp_prefix__}sy = ${__temp_prefix__}base-1;
1662       } else {
1663         ${__temp_prefix__}base = integer_divide_table[${__temp_prefix__}ady].ptr[${__temp_prefix__}adx];
1664         ${__temp_prefix__}sy = ${__temp_prefix__}base+1;
1665       }
1666     } else {
1667       ${__temp_prefix__}base = ${__temp_prefix__}dy/${__temp_prefix__}adx;
1668       ${__temp_prefix__}sy = ${__temp_prefix__}base+(${__temp_prefix__}dy < 0 ? -1 : 1);
1669     }
1670   } else {
1671     ${__temp_prefix__}base = ${__temp_prefix__}dy/${__temp_prefix__}adx;
1672     ${__temp_prefix__}sy = ${__temp_prefix__}base+(${__temp_prefix__}dy < 0 ? -1 : 1);
1673   }
1674   ${__temp_prefix__}ady -= mixin(ABS!"${__temp_prefix__}base")*${__temp_prefix__}adx;
1675   if (${x1} > ${n}) ${x1} = ${n};
1676   if (${__temp_prefix__}x < ${x1}) {
1677     mixin(LINE_OP!("${output}[${__temp_prefix__}x]", "inverse_db_table[${__temp_prefix__}y]"));
1678     for (++${__temp_prefix__}x; ${__temp_prefix__}x < ${x1}; ++${__temp_prefix__}x) {
1679       ${__temp_prefix__}err += ${__temp_prefix__}ady;
1680       if (${__temp_prefix__}err >= ${__temp_prefix__}adx) {
1681         ${__temp_prefix__}err -= ${__temp_prefix__}adx;
1682         ${__temp_prefix__}y += ${__temp_prefix__}sy;
1683       } else {
1684         ${__temp_prefix__}y += ${__temp_prefix__}base;
1685       }
1686       mixin(LINE_OP!("${output}[${__temp_prefix__}x]", "inverse_db_table[${__temp_prefix__}y]"));
1687     }
1688   }
1689   /*
1690   mixin(LINE_OP!("${output}[${__temp_prefix__}x]", "inverse_db_table[${__temp_prefix__}y]"));
1691   for (++${__temp_prefix__}x; ${__temp_prefix__}x < ${x1}; ++${__temp_prefix__}x) {
1692     ${__temp_prefix__}err += ${__temp_prefix__}ady;
1693     if (${__temp_prefix__}err >= ${__temp_prefix__}adx) {
1694       ${__temp_prefix__}err -= ${__temp_prefix__}adx;
1695       ${__temp_prefix__}y += ${__temp_prefix__}sy;
1696     } else {
1697       ${__temp_prefix__}y += ${__temp_prefix__}base;
1698     }
1699     mixin(LINE_OP!("${output}[${__temp_prefix__}x]", "inverse_db_table[${__temp_prefix__}y]"));
1700   }
1701   */
1702 }}.cmacroFixVars!("output", "x0", "y0", "x1", "y1", "n")(output, x0, y0, x1, y1, n);
1703 
1704 int residue_decode (VorbisDecoder* f, Codebook* book, float* target, int offset, int n, int rtype) {
1705   if (rtype == 0) {
1706     int step = n/book.dimensions;
1707     foreach (immutable k; 0..step) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return false;
1708   } else {
1709     for (int k = 0; k < n; ) {
1710       if (!codebook_decode(f, book, target+offset, n-k)) return false;
1711       k += book.dimensions;
1712       offset += book.dimensions;
1713     }
1714   }
1715   return true;
1716 }
1717 
1718 void decode_residue (
1719 VorbisDecoder* f,
1720 ref float*[STB_VORBIS_MAX_CHANNELS] residue_buffers,
1721 int ch,
1722 int n,
1723 int rn,
1724 ubyte* do_not_decode) {
1725   
1726   import core.stdc.stdlib : alloca;
1727   import core.stdc.string : memset;
1728 
1729   Residue* r = f.residue_config+rn;
1730   int rtype = f.residue_types.ptr[rn];
1731   int c = r.classbook;
1732   int classwords = f.codebooks[c].dimensions;
1733   int n_read = r.end-r.begin;
1734   int part_read = n_read/r.part_size;
1735   uint temp_alloc_point = temp_alloc_save(f);
1736   version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1737     int** classifications = cast(int**)mixin(temp_block_array!("f.vrchannels", "part_read*int.sizeof"));
1738   } else {
1739     ubyte*** part_classdata =
1740         cast(ubyte***)mixin(temp_block_array!("f.vrchannels", "part_read*cast(int)(ubyte*).sizeof"));
1741   }
1742 
1743   //stb_prof(2);
1744   foreach (immutable i; 0..ch) if (!do_not_decode[i]) memset(residue_buffers.ptr[i], 0, float.sizeof*n);
1745 
1746   if (rtype == 2 && ch != 1) {
1747     int j = void;
1748     for (j = 0; j < ch; ++j) if (!do_not_decode[j]) break;
1749     if (j == ch) goto done;
1750 
1751     //stb_prof(3);
1752     foreach (immutable pass; 0..8) {
1753       int pcount = 0, class_set = 0;
1754       if (ch == 2) {
1755         //stb_prof(13);
1756         while (pcount < part_read) {
1757           int z = r.begin+pcount*r.part_size;
1758           int c_inter = (z&1), p_inter = z>>1;
1759           if (pass == 0) {
1760             Codebook *cc = f.codebooks+r.classbook;
1761             int q;
1762             mixin(DECODE!("q", "cc"));
1763             if (q == EOP) goto done;
1764             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1765               for (int i = classwords-1; i >= 0; --i) {
1766                 classifications[0].ptr[i+pcount] = q%r.classifications;
1767                 q /= r.classifications;
1768               }
1769             } else {
1770               part_classdata[0][class_set] = r.classdata[q];
1771             }
1772           }
1773           //stb_prof(5);
1774           for (int i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
1775             int zz = r.begin+pcount*r.part_size;
1776             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1777               int cc = classifications[0].ptr[pcount];
1778             } else {
1779               int cc = part_classdata[0][class_set][i];
1780             }
1781             int b = r.residue_books[cc].ptr[pass];
1782             if (b >= 0) {
1783               Codebook* book = f.codebooks+b;
1784               //stb_prof(20); // accounts for X time
1785               version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {
1786                 if (!codebook_decode_deinterleave_repeat(
1787                     f, book, residue_buffers, ch, &c_inter, &p_inter, n, r.part_size)
1788                     )goto done;
1789               } else {
1790                 // saves 1%
1791                 //if (!codebook_decode_deinterleave_repeat_2(f, book, residue_buffers, &c_inter, &p_inter, n, r.part_size)) goto done; // according to C source
1792                 if (!codebook_decode_deinterleave_repeat(
1793                     f, book, residue_buffers, ch, &c_inter, &p_inter, n, r.part_size)
1794                     ) goto done;
1795               }
1796               //stb_prof(7);
1797             } else {
1798               zz += r.part_size;
1799               c_inter = zz&1;
1800               p_inter = zz>>1;
1801             }
1802           }
1803           //stb_prof(8);
1804           version(STB_VORBIS_DIVIDES_IN_RESIDUE) {} else {
1805             ++class_set;
1806           }
1807         }
1808       } else if (ch == 1) {
1809         while (pcount < part_read) {
1810           int z = r.begin+pcount*r.part_size;
1811           int c_inter = 0, p_inter = z;
1812           if (pass == 0) {
1813             Codebook* cc = f.codebooks+r.classbook;
1814             int q;
1815             mixin(DECODE!("q", "cc"));
1816             if (q == EOP) goto done;
1817             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1818               for (int i = classwords-1; i >= 0; --i) {
1819                 classifications[0].ptr[i+pcount] = q%r.classifications;
1820                 q /= r.classifications;
1821               }
1822             } else {
1823               part_classdata[0][class_set] = r.classdata[q];
1824             }
1825           }
1826           for (int i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
1827             int zz = r.begin+pcount*r.part_size;
1828             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1829               int cc = classifications[0].ptr[pcount];
1830             } else {
1831               int cc = part_classdata[0][class_set][i];
1832             }
1833             int b = r.residue_books[cc].ptr[pass];
1834             if (b >= 0) {
1835               Codebook* book = f.codebooks+b;
1836               //stb_prof(22);
1837               if (!codebook_decode_deinterleave_repeat(
1838                     f, book, residue_buffers, ch, &c_inter, &p_inter, n, r.part_size)
1839                   ) goto done;
1840               //stb_prof(3);
1841             } else {
1842               zz += r.part_size;
1843               c_inter = 0;
1844               p_inter = zz;
1845             }
1846           }
1847           version(STB_VORBIS_DIVIDES_IN_RESIDUE) {} else {
1848             ++class_set;
1849           }
1850         }
1851       } else {
1852         while (pcount < part_read) {
1853           int z = r.begin+pcount*r.part_size;
1854           int c_inter = z%ch, p_inter = z/ch;
1855           if (pass == 0) {
1856             Codebook* cc = f.codebooks+r.classbook;
1857             int q;
1858             mixin(DECODE!("q", "cc"));
1859             if (q == EOP) goto done;
1860             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1861               for (int i = classwords-1; i >= 0; --i) {
1862                 classifications[0].ptr[i+pcount] = q%r.classifications;
1863                 q /= r.classifications;
1864               }
1865             } else {
1866               part_classdata[0][class_set] = r.classdata[q];
1867             }
1868           }
1869           for (int i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
1870             int zz = r.begin+pcount*r.part_size;
1871             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1872               int cc = classifications[0].ptr[pcount];
1873             } else {
1874               int cc = part_classdata[0][class_set][i];
1875             }
1876             int b = r.residue_books[cc].ptr[pass];
1877             if (b >= 0) {
1878               Codebook* book = f.codebooks+b;
1879               //stb_prof(22);
1880               if (!codebook_decode_deinterleave_repeat(
1881                    f, book, residue_buffers, ch, &c_inter, &p_inter, n, r.part_size)
1882                   ) goto done;
1883               //stb_prof(3);
1884             } else {
1885               zz += r.part_size;
1886               c_inter = zz%ch;
1887               p_inter = zz/ch;
1888             }
1889           }
1890           version(STB_VORBIS_DIVIDES_IN_RESIDUE) {} else {
1891             ++class_set;
1892           }
1893         }
1894       }
1895     }
1896     goto done;
1897   }
1898   //stb_prof(9);
1899 
1900   foreach (immutable pass; 0..8) {
1901     int pcount = 0, class_set=0;
1902     while (pcount < part_read) {
1903       if (pass == 0) {
1904         foreach (immutable j; 0..ch) {
1905           if (!do_not_decode[j]) {
1906             Codebook* cc = f.codebooks+r.classbook;
1907             int temp;
1908             mixin(DECODE!("temp", "cc"));
1909             if (temp == EOP) goto done;
1910             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1911               for (int i = classwords-1; i >= 0; --i) {
1912                 classifications[j].ptr[i+pcount] = temp%r.classifications;
1913                 temp /= r.classifications;
1914               }
1915             } else {
1916               part_classdata[j][class_set] = r.classdata[temp];
1917             }
1918           }
1919         }
1920       }
1921       for (int i = 0; i < classwords && pcount < part_read; ++i, ++pcount) {
1922         foreach (immutable j; 0..ch) {
1923           if (!do_not_decode[j]) {
1924             version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
1925               int cc = classifications[j].ptr[pcount];
1926             } else {
1927               int cc = part_classdata[j][class_set][i];
1928             }
1929             int b = r.residue_books[cc].ptr[pass];
1930             if (b >= 0) {
1931               float* target = residue_buffers.ptr[j];
1932               int offset = r.begin+pcount*r.part_size;
1933               int nn = r.part_size;
1934               Codebook* book = f.codebooks+b;
1935               if (!residue_decode(f, book, target, offset, nn, rtype)) goto done;
1936             }
1937           }
1938         }
1939       }
1940       version(STB_VORBIS_DIVIDES_IN_RESIDUE) {} else {
1941         ++class_set;
1942       }
1943     }
1944   }
1945  done:
1946   //stb_prof(0);
1947   version(STB_VORBIS_DIVIDES_IN_RESIDUE) temp_free(f, classifications); else temp_free(f, part_classdata);
1948   temp_alloc_restore(f, temp_alloc_point);
1949 }
1950 
1951 
1952 // the following were split out into separate functions while optimizing;
1953 // they could be pushed back up but eh. __forceinline showed no change;
1954 // they're probably already being inlined.
1955 void imdct_step3_iter0_loop (int n, float* e, int i_off, int k_off, float* A) {
1956   float* ee0 = e+i_off;
1957   float* ee2 = ee0+k_off;
1958   debug(stb_vorbis) assert((n&3) == 0);
1959   foreach (immutable _; 0..n>>2) {
1960     float k00_20, k01_21;
1961     k00_20 = ee0[ 0]-ee2[ 0];
1962     k01_21 = ee0[-1]-ee2[-1];
1963     ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0]+ee2[ 0];
1964     ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1]+ee2[-1];
1965     ee2[ 0] = k00_20*A[0]-k01_21*A[1];
1966     ee2[-1] = k01_21*A[0]+k00_20*A[1];
1967     A += 8;
1968 
1969     k00_20 = ee0[-2]-ee2[-2];
1970     k01_21 = ee0[-3]-ee2[-3];
1971     ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2]+ee2[-2];
1972     ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3]+ee2[-3];
1973     ee2[-2] = k00_20*A[0]-k01_21*A[1];
1974     ee2[-3] = k01_21*A[0]+k00_20*A[1];
1975     A += 8;
1976 
1977     k00_20 = ee0[-4]-ee2[-4];
1978     k01_21 = ee0[-5]-ee2[-5];
1979     ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4]+ee2[-4];
1980     ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5]+ee2[-5];
1981     ee2[-4] = k00_20*A[0]-k01_21*A[1];
1982     ee2[-5] = k01_21*A[0]+k00_20*A[1];
1983     A += 8;
1984 
1985     k00_20 = ee0[-6]-ee2[-6];
1986     k01_21 = ee0[-7]-ee2[-7];
1987     ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6]+ee2[-6];
1988     ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7]+ee2[-7];
1989     ee2[-6] = k00_20*A[0]-k01_21*A[1];
1990     ee2[-7] = k01_21*A[0]+k00_20*A[1];
1991     A += 8;
1992     ee0 -= 8;
1993     ee2 -= 8;
1994   }
1995 }
1996 
1997 void imdct_step3_inner_r_loop (int lim, float* e, int d0, int k_off, float* A, int k1) {
1998   float k00_20, k01_21;
1999   float* e0 = e+d0;
2000   float* e2 = e0+k_off;
2001   foreach (immutable _; 0..lim>>2) {
2002     k00_20 = e0[-0]-e2[-0];
2003     k01_21 = e0[-1]-e2[-1];
2004     e0[-0] += e2[-0];//e0[-0] = e0[-0]+e2[-0];
2005     e0[-1] += e2[-1];//e0[-1] = e0[-1]+e2[-1];
2006     e2[-0] = (k00_20)*A[0]-(k01_21)*A[1];
2007     e2[-1] = (k01_21)*A[0]+(k00_20)*A[1];
2008 
2009     A += k1;
2010 
2011     k00_20 = e0[-2]-e2[-2];
2012     k01_21 = e0[-3]-e2[-3];
2013     e0[-2] += e2[-2];//e0[-2] = e0[-2]+e2[-2];
2014     e0[-3] += e2[-3];//e0[-3] = e0[-3]+e2[-3];
2015     e2[-2] = (k00_20)*A[0]-(k01_21)*A[1];
2016     e2[-3] = (k01_21)*A[0]+(k00_20)*A[1];
2017 
2018     A += k1;
2019 
2020     k00_20 = e0[-4]-e2[-4];
2021     k01_21 = e0[-5]-e2[-5];
2022     e0[-4] += e2[-4];//e0[-4] = e0[-4]+e2[-4];
2023     e0[-5] += e2[-5];//e0[-5] = e0[-5]+e2[-5];
2024     e2[-4] = (k00_20)*A[0]-(k01_21)*A[1];
2025     e2[-5] = (k01_21)*A[0]+(k00_20)*A[1];
2026 
2027     A += k1;
2028 
2029     k00_20 = e0[-6]-e2[-6];
2030     k01_21 = e0[-7]-e2[-7];
2031     e0[-6] += e2[-6];//e0[-6] = e0[-6]+e2[-6];
2032     e0[-7] += e2[-7];//e0[-7] = e0[-7]+e2[-7];
2033     e2[-6] = (k00_20)*A[0]-(k01_21)*A[1];
2034     e2[-7] = (k01_21)*A[0]+(k00_20)*A[1];
2035 
2036     e0 -= 8;
2037     e2 -= 8;
2038 
2039     A += k1;
2040   }
2041 }
2042 
2043 void imdct_step3_inner_s_loop (int n, float* e, int i_off, int k_off, float* A, int a_off, int k0) {
2044   float A0 = A[0];
2045   float A1 = A[0+1];
2046   float A2 = A[0+a_off];
2047   float A3 = A[0+a_off+1];
2048   float A4 = A[0+a_off*2+0];
2049   float A5 = A[0+a_off*2+1];
2050   float A6 = A[0+a_off*3+0];
2051   float A7 = A[0+a_off*3+1];
2052   float k00, k11;
2053   float *ee0 = e  +i_off;
2054   float *ee2 = ee0+k_off;
2055   foreach (immutable _; 0..n) {
2056     k00 = ee0[ 0]-ee2[ 0];
2057     k11 = ee0[-1]-ee2[-1];
2058     ee0[ 0] = ee0[ 0]+ee2[ 0];
2059     ee0[-1] = ee0[-1]+ee2[-1];
2060     ee2[ 0] = (k00)*A0-(k11)*A1;
2061     ee2[-1] = (k11)*A0+(k00)*A1;
2062 
2063     k00 = ee0[-2]-ee2[-2];
2064     k11 = ee0[-3]-ee2[-3];
2065     ee0[-2] = ee0[-2]+ee2[-2];
2066     ee0[-3] = ee0[-3]+ee2[-3];
2067     ee2[-2] = (k00)*A2-(k11)*A3;
2068     ee2[-3] = (k11)*A2+(k00)*A3;
2069 
2070     k00 = ee0[-4]-ee2[-4];
2071     k11 = ee0[-5]-ee2[-5];
2072     ee0[-4] = ee0[-4]+ee2[-4];
2073     ee0[-5] = ee0[-5]+ee2[-5];
2074     ee2[-4] = (k00)*A4-(k11)*A5;
2075     ee2[-5] = (k11)*A4+(k00)*A5;
2076 
2077     k00 = ee0[-6]-ee2[-6];
2078     k11 = ee0[-7]-ee2[-7];
2079     ee0[-6] = ee0[-6]+ee2[-6];
2080     ee0[-7] = ee0[-7]+ee2[-7];
2081     ee2[-6] = (k00)*A6-(k11)*A7;
2082     ee2[-7] = (k11)*A6+(k00)*A7;
2083 
2084     ee0 -= k0;
2085     ee2 -= k0;
2086   }
2087 }
2088 
2089 // this was forceinline
2090 //void iter_54(float *z)
2091 enum iter_54(string z) = q{{
2092   auto ${__temp_prefix__}z = (${z});
2093   float ${__temp_prefix__}k00, ${__temp_prefix__}k11, ${__temp_prefix__}k22, ${__temp_prefix__}k33;
2094   float ${__temp_prefix__}y0, ${__temp_prefix__}y1, ${__temp_prefix__}y2, ${__temp_prefix__}y3;
2095 
2096   ${__temp_prefix__}k00 = ${__temp_prefix__}z[ 0]-${__temp_prefix__}z[-4];
2097   ${__temp_prefix__}y0  = ${__temp_prefix__}z[ 0]+${__temp_prefix__}z[-4];
2098   ${__temp_prefix__}y2  = ${__temp_prefix__}z[-2]+${__temp_prefix__}z[-6];
2099   ${__temp_prefix__}k22 = ${__temp_prefix__}z[-2]-${__temp_prefix__}z[-6];
2100 
2101   ${__temp_prefix__}z[-0] = ${__temp_prefix__}y0+${__temp_prefix__}y2;   // z0+z4+z2+z6
2102   ${__temp_prefix__}z[-2] = ${__temp_prefix__}y0-${__temp_prefix__}y2;   // z0+z4-z2-z6
2103 
2104   // done with ${__temp_prefix__}y0, ${__temp_prefix__}y2
2105 
2106   ${__temp_prefix__}k33 = ${__temp_prefix__}z[-3]-${__temp_prefix__}z[-7];
2107 
2108   ${__temp_prefix__}z[-4] = ${__temp_prefix__}k00+${__temp_prefix__}k33; // z0-z4+z3-z7
2109   ${__temp_prefix__}z[-6] = ${__temp_prefix__}k00-${__temp_prefix__}k33; // z0-z4-z3+z7
2110 
2111   // done with ${__temp_prefix__}k33
2112 
2113   ${__temp_prefix__}k11 = ${__temp_prefix__}z[-1]-${__temp_prefix__}z[-5];
2114   ${__temp_prefix__}y1  = ${__temp_prefix__}z[-1]+${__temp_prefix__}z[-5];
2115   ${__temp_prefix__}y3  = ${__temp_prefix__}z[-3]+${__temp_prefix__}z[-7];
2116 
2117   ${__temp_prefix__}z[-1] = ${__temp_prefix__}y1+${__temp_prefix__}y3;   // z1+z5+z3+z7
2118   ${__temp_prefix__}z[-3] = ${__temp_prefix__}y1-${__temp_prefix__}y3;   // z1+z5-z3-z7
2119   ${__temp_prefix__}z[-5] = ${__temp_prefix__}k11-${__temp_prefix__}k22; // z1-z5+z2-z6
2120   ${__temp_prefix__}z[-7] = ${__temp_prefix__}k11+${__temp_prefix__}k22; // z1-z5-z2+z6
2121 }}.cmacroFixVars!"z"(z);
2122 
2123 static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
2124 {
2125     int a_off = base_n >> 3;
2126     float A2 = A[0+a_off];
2127     float *z = e + i_off;
2128     float *base = z - 16 * n;
2129 
2130     while (z > base) {
2131         float k00,k11;
2132         float l00,l11;
2133 
2134         k00    = z[-0] - z[ -8];
2135         k11    = z[-1] - z[ -9];
2136         l00    = z[-2] - z[-10];
2137         l11    = z[-3] - z[-11];
2138         z[ -0] = z[-0] + z[ -8];
2139         z[ -1] = z[-1] + z[ -9];
2140         z[ -2] = z[-2] + z[-10];
2141         z[ -3] = z[-3] + z[-11];
2142         z[ -8] = k00;
2143         z[ -9] = k11;
2144         z[-10] = (l00+l11) * A2;
2145         z[-11] = (l11-l00) * A2;
2146 
2147         k00    = z[ -4] - z[-12];
2148         k11    = z[ -5] - z[-13];
2149         l00    = z[ -6] - z[-14];
2150         l11    = z[ -7] - z[-15];
2151         z[ -4] = z[ -4] + z[-12];
2152         z[ -5] = z[ -5] + z[-13];
2153         z[ -6] = z[ -6] + z[-14];
2154         z[ -7] = z[ -7] + z[-15];
2155         z[-12] = k11;
2156         z[-13] = -k00;
2157         z[-14] = (l11-l00) * A2;
2158         z[-15] = (l00+l11) * -A2;
2159 
2160         mixin(iter_54!"z");
2161         mixin(iter_54!"z-8");
2162         z -= 16;
2163     }
2164 }
2165 
2166 void inverse_mdct (float* buffer, int n, VorbisDecoder* f, int blocktype) {
2167   import core.stdc.stdlib : alloca;
2168 
2169   int n2 = n>>1, n4 = n>>2, n8 = n>>3, l;
2170   int ld;
2171   // @OPTIMIZE: reduce register pressure by using fewer variables?
2172   int save_point = temp_alloc_save(f);
2173   float *buf2;
2174   buf2 = cast(float*)mixin(temp_alloc!("n2*float.sizeof"));
2175   float *u = null, v = null;
2176   // twiddle factors
2177   float *A = f.A.ptr[blocktype];
2178 
2179   // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
2180   // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
2181 
2182   // kernel from paper
2183 
2184 
2185   // merged:
2186   //   copy and reflect spectral data
2187   //   step 0
2188 
2189   // note that it turns out that the items added together during
2190   // this step are, in fact, being added to themselves (as reflected
2191   // by step 0). inexplicable inefficiency! this became obvious
2192   // once I combined the passes.
2193 
2194   // so there's a missing 'times 2' here (for adding X to itself).
2195   // this propogates through linearly to the end, where the numbers
2196   // are 1/2 too small, and need to be compensated for.
2197 
2198   {
2199     float* d, e, AA, e_stop;
2200     d = &buf2[n2-2];
2201     AA = A;
2202     e = &buffer[0];
2203     e_stop = &buffer[n2];
2204     while (e != e_stop) {
2205       d[1] = (e[0]*AA[0]-e[2]*AA[1]);
2206       d[0] = (e[0]*AA[1]+e[2]*AA[0]);
2207       d -= 2;
2208       AA += 2;
2209       e += 4;
2210     }
2211     e = &buffer[n2-3];
2212     while (d >= buf2) {
2213       d[1] = (-e[2]*AA[0]- -e[0]*AA[1]);
2214       d[0] = (-e[2]*AA[1]+ -e[0]*AA[0]);
2215       d -= 2;
2216       AA += 2;
2217       e -= 4;
2218     }
2219   }
2220 
2221   // now we use symbolic names for these, so that we can
2222   // possibly swap their meaning as we change which operations
2223   // are in place
2224 
2225   u = buffer;
2226   v = buf2;
2227 
2228   // step 2    (paper output is w, now u)
2229   // this could be in place, but the data ends up in the wrong
2230   // place... _somebody_'s got to swap it, so this is nominated
2231   {
2232     float* AA = &A[n2-8];
2233     float* d0, d1, e0, e1;
2234     e0 = &v[n4];
2235     e1 = &v[0];
2236     d0 = &u[n4];
2237     d1 = &u[0];
2238     while (AA >= A) {
2239       float v40_20, v41_21;
2240 
2241       v41_21 = e0[1]-e1[1];
2242       v40_20 = e0[0]-e1[0];
2243       d0[1]  = e0[1]+e1[1];
2244       d0[0]  = e0[0]+e1[0];
2245       d1[1]  = v41_21*AA[4]-v40_20*AA[5];
2246       d1[0]  = v40_20*AA[4]+v41_21*AA[5];
2247 
2248       v41_21 = e0[3]-e1[3];
2249       v40_20 = e0[2]-e1[2];
2250       d0[3]  = e0[3]+e1[3];
2251       d0[2]  = e0[2]+e1[2];
2252       d1[3]  = v41_21*AA[0]-v40_20*AA[1];
2253       d1[2]  = v40_20*AA[0]+v41_21*AA[1];
2254 
2255       AA -= 8;
2256 
2257       d0 += 4;
2258       d1 += 4;
2259       e0 += 4;
2260       e1 += 4;
2261     }
2262   }
2263 
2264   // step 3
2265   ld = ilog(n)-1; // ilog is off-by-one from normal definitions
2266 
2267   // optimized step 3:
2268 
2269   // the original step3 loop can be nested r inside s or s inside r;
2270   // it's written originally as s inside r, but this is dumb when r
2271   // iterates many times, and s few. So I have two copies of it and
2272   // switch between them halfway.
2273 
2274   // this is iteration 0 of step 3
2275   imdct_step3_iter0_loop(n>>4, u, n2-1-n4*0, -(n>>3), A);
2276   imdct_step3_iter0_loop(n>>4, u, n2-1-n4*1, -(n>>3), A);
2277 
2278   // this is iteration 1 of step 3
2279   imdct_step3_inner_r_loop(n>>5, u, n2-1-n8*0, -(n>>4), A, 16);
2280   imdct_step3_inner_r_loop(n>>5, u, n2-1-n8*1, -(n>>4), A, 16);
2281   imdct_step3_inner_r_loop(n>>5, u, n2-1-n8*2, -(n>>4), A, 16);
2282   imdct_step3_inner_r_loop(n>>5, u, n2-1-n8*3, -(n>>4), A, 16);
2283 
2284   l = 2;
2285   for (; l < (ld-3)>>1; ++l) {
2286     int k0 = n>>(l+2), k0_2 = k0>>1;
2287     int lim = 1<<(l+1);
2288     foreach (int i; 0..lim) imdct_step3_inner_r_loop(n>>(l+4), u, n2-1-k0*i, -k0_2, A, 1<<(l+3));
2289   }
2290 
2291   for (; l < ld-6; ++l) {
2292     int k0 = n>>(l+2), k1 = 1<<(l+3), k0_2 = k0>>1;
2293     int rlim = n>>(l+6);
2294     int lim = 1<<(l+1);
2295     int i_off;
2296     float *A0 = A;
2297     i_off = n2-1;
2298     foreach (immutable _; 0..rlim) {
2299       imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
2300       A0 += k1*4;
2301       i_off -= 8;
2302     }
2303   }
2304 
2305   // iterations with count:
2306   //   ld-6,-5,-4 all interleaved together
2307   //       the big win comes from getting rid of needless flops
2308   //         due to the constants on pass 5 & 4 being all 1 and 0;
2309   //       combining them to be simultaneous to improve cache made little difference
2310   imdct_step3_inner_s_loop_ld654(n>>5, u, n2-1, A, n);
2311 
2312   // output is u
2313 
2314   // step 4, 5, and 6
2315   // cannot be in-place because of step 5
2316   {
2317     ushort *bitrev = f.bit_reverse.ptr[blocktype];
2318     // weirdly, I'd have thought reading sequentially and writing
2319     // erratically would have been better than vice-versa, but in
2320     // fact that's not what my testing showed. (That is, with
2321     // j = bitreverse(i), do you read i and write j, or read j and write i.)
2322     float *d0 = &v[n4-4];
2323     float *d1 = &v[n2-4];
2324     int k4;
2325     while (d0 >= v) {
2326       k4 = bitrev[0];
2327       d1[3] = u[k4+0];
2328       d1[2] = u[k4+1];
2329       d0[3] = u[k4+2];
2330       d0[2] = u[k4+3];
2331 
2332       k4 = bitrev[1];
2333       d1[1] = u[k4+0];
2334       d1[0] = u[k4+1];
2335       d0[1] = u[k4+2];
2336       d0[0] = u[k4+3];
2337 
2338       d0 -= 4;
2339       d1 -= 4;
2340       bitrev += 2;
2341     }
2342   }
2343   // (paper output is u, now v)
2344 
2345 
2346   // data must be in buf2
2347   debug(stb_vorbis) assert(v == buf2);
2348 
2349   // step 7   (paper output is v, now v)
2350   // this is now in place
2351   {
2352     float a02, a11, b0, b1, b2, b3;
2353     float* C = f.C.ptr[blocktype];
2354     float* d, e;
2355     d = v;
2356     e = v+n2-4;
2357     while (d < e) {
2358       a02 = d[0]-e[2];
2359       a11 = d[1]+e[3];
2360 
2361       b0 = C[1]*a02+C[0]*a11;
2362       b1 = C[1]*a11-C[0]*a02;
2363 
2364       b2 = d[0]+e[ 2];
2365       b3 = d[1]-e[ 3];
2366 
2367       d[0] = b2+b0;
2368       d[1] = b3+b1;
2369       e[2] = b2-b0;
2370       e[3] = b1-b3;
2371 
2372       a02 = d[2]-e[0];
2373       a11 = d[3]+e[1];
2374 
2375       b0 = C[3]*a02+C[2]*a11;
2376       b1 = C[3]*a11-C[2]*a02;
2377 
2378       b2 = d[2]+e[ 0];
2379       b3 = d[3]-e[ 1];
2380 
2381       d[2] = b2+b0;
2382       d[3] = b3+b1;
2383       e[0] = b2-b0;
2384       e[1] = b1-b3;
2385 
2386       C += 4;
2387       d += 4;
2388       e -= 4;
2389     }
2390   }
2391 
2392   // data must be in buf2
2393 
2394 
2395   // step 8+decode   (paper output is X, now buffer)
2396   // this generates pairs of data a la 8 and pushes them directly through
2397   // the decode kernel (pushing rather than pulling) to avoid having
2398   // to make another pass later
2399 
2400   // this cannot POSSIBLY be in place, so we refer to the buffers directly
2401   {
2402     float p0, p1, p2, p3;
2403     float* d0, d1, d2, d3;
2404     float* B = f.B.ptr[blocktype]+n2-8;
2405     float* e = buf2+n2-8;
2406     d0 = &buffer[0];
2407     d1 = &buffer[n2-4];
2408     d2 = &buffer[n2];
2409     d3 = &buffer[n-4];
2410     while (e >= v) {
2411       p3 =  e[6]*B[7]-e[7]*B[6];
2412       p2 = -e[6]*B[6]-e[7]*B[7];
2413 
2414       d0[0] =   p3;
2415       d1[3] =  -p3;
2416       d2[0] =   p2;
2417       d3[3] =   p2;
2418 
2419       p1 =  e[4]*B[5]-e[5]*B[4];
2420       p0 = -e[4]*B[4]-e[5]*B[5];
2421 
2422       d0[1] =   p1;
2423       d1[2] = - p1;
2424       d2[1] =   p0;
2425       d3[2] =   p0;
2426 
2427       p3 =  e[2]*B[3]-e[3]*B[2];
2428       p2 = -e[2]*B[2]-e[3]*B[3];
2429 
2430       d0[2] =   p3;
2431       d1[1] = - p3;
2432       d2[2] =   p2;
2433       d3[1] =   p2;
2434 
2435       p1 =  e[0]*B[1]-e[1]*B[0];
2436       p0 = -e[0]*B[0]-e[1]*B[1];
2437 
2438       d0[3] =   p1;
2439       d1[0] = - p1;
2440       d2[3] =   p0;
2441       d3[0] =   p0;
2442 
2443       B -= 8;
2444       e -= 8;
2445       d0 += 4;
2446       d2 += 4;
2447       d1 -= 4;
2448       d3 -= 4;
2449     }
2450   }
2451 
2452   temp_free(f, buf2);
2453   temp_alloc_restore(f, save_point);
2454 }
2455 
2456 float *get_window (VorbisDecoder* f, int len) {
2457   len <<= 1;
2458   if (len == f.blocksize_0) return f.window.ptr[0];
2459   if (len == f.blocksize_1) return f.window.ptr[1];
2460   assert(0);
2461 }
2462 
2463 version(STB_VORBIS_NO_DEFER_FLOOR) {
2464   alias YTYPE = int;
2465 } else {
2466   alias YTYPE = short;
2467 }
2468 
2469 int do_floor (VorbisDecoder* f, Mapping* map, int i, int n, float* target, YTYPE* finalY, ubyte* step2_flag) {
2470   int n2 = n>>1;
2471   int s = map.chan[i].mux, floor;
2472   floor = map.submap_floor.ptr[s];
2473   if (f.floor_types.ptr[floor] == 0) {
2474     return error(f, STBVorbisError.invalid_stream);
2475   } else {
2476     Floor1* g = &f.floor_config[floor].floor1;
2477     int lx = 0, ly = finalY[0]*g.floor1_multiplier;
2478     foreach (immutable q; 1..g.values) {
2479       int j = g.sorted_order.ptr[q];
2480       version(STB_VORBIS_NO_DEFER_FLOOR) {
2481         auto cond = step2_flag[j];
2482       } else {
2483         auto cond = (finalY[j] >= 0);
2484       }
2485       if (cond) {
2486         int hy = finalY[j]*g.floor1_multiplier;
2487         int hx = g.xList.ptr[j];
2488         if (lx != hx) { mixin(draw_line!("target", "lx", "ly", "hx", "hy", "n2")); }
2489         lx = hx; ly = hy;
2490       }
2491     }
2492     if (lx < n2) {
2493       // optimization of: draw_line(target, lx, ly, n, ly, n2);
2494       foreach (immutable j; lx..n2) { mixin(LINE_OP!("target[j]", "inverse_db_table[ly]")); }
2495     }
2496   }
2497   return true;
2498 }
2499 
2500 // The meaning of "left" and "right"
2501 //
2502 // For a given frame:
2503 //     we compute samples from 0..n
2504 //     window_center is n/2
2505 //     we'll window and mix the samples from left_start to left_end with data from the previous frame
2506 //     all of the samples from left_end to right_start can be output without mixing; however,
2507 //        this interval is 0-length except when transitioning between short and long frames
2508 //     all of the samples from right_start to right_end need to be mixed with the next frame,
2509 //        which we don't have, so those get saved in a buffer
2510 //     frame N's right_end-right_start, the number of samples to mix with the next frame,
2511 //        has to be the same as frame N+1's left_end-left_start (which they are by
2512 //        construction)
2513 
2514 int vorbis_decode_initial (
2515 VorbisDecoder* f,
2516 int* p_left_start,
2517 int* p_left_end,
2518 int* p_right_start,
2519 int* p_right_end,
2520 int* mode) {
2521   
2522   Mode *m;
2523   int i, n, prev, next, window_center;
2524   f.channel_buffer_start = f.channel_buffer_end = 0;
2525 
2526  retry:
2527   if (f.eof) return false;
2528   if (!maybe_start_packet(f)) return false;
2529   // check packet type
2530   if (get_bits!1(f) != 0) {
2531     /+if (f.push_mode) return error(f, STBVorbisError.bad_packet_type);+/
2532     while (EOP != get8_packet(f)) {}
2533     goto retry;
2534   }
2535 
2536   //debug(stb_vorbis) if (f.alloc.alloc_buffer) assert(f.alloc.alloc_buffer_length_in_bytes == f.temp_offset);
2537 
2538   i = get_bits_main(f, ilog(f.mode_count-1));
2539   if (i == EOP) return false;
2540   if (i >= f.mode_count) return false;
2541   *mode = i;
2542   m = f.mode_config.ptr+i;
2543   if (m.blockflag) {
2544     n = f.blocksize_1;
2545     prev = get_bits!1(f);
2546     next = get_bits!1(f);
2547   } else {
2548     prev = next = 0;
2549     n = f.blocksize_0;
2550   }
2551 
2552   // WINDOWING
2553   window_center = n>>1;
2554   if (m.blockflag && !prev) {
2555     *p_left_start = (n-f.blocksize_0)>>2;
2556     *p_left_end   = (n+f.blocksize_0)>>2;
2557   } else {
2558     *p_left_start = 0;
2559     *p_left_end   = window_center;
2560   }
2561   if (m.blockflag && !next) {
2562     *p_right_start = (n*3-f.blocksize_0)>>2;
2563     *p_right_end   = (n*3+f.blocksize_0)>>2;
2564   } else {
2565     *p_right_start = window_center;
2566     *p_right_end   = n;
2567   }
2568   return true;
2569 }
2570 
2571 int vorbis_decode_packet_rest (
2572 VorbisDecoder* f,
2573 int* len,
2574 Mode* m,
2575 int left_start,
2576 int left_end,
2577 int right_start,
2578 int right_end,
2579 int* p_left) {
2580   import core.stdc.string : memcpy, memset;
2581 
2582   Mapping* map;
2583   int n, n2;
2584   int[256] zero_channel;
2585   int[256] really_zero_channel;
2586 
2587   // WINDOWING
2588   n = f.blocksize.ptr[m.blockflag];
2589   map = &f.mapping[m.mapping];
2590 
2591   // FLOORS
2592   n2 = n>>1;
2593 
2594   //stb_prof(1);
2595   foreach (immutable i; 0..f.vrchannels) {
2596     int s = map.chan[i].mux, floor;
2597     zero_channel[i] = false;
2598     floor = map.submap_floor.ptr[s];
2599     if (f.floor_types.ptr[floor] == 0) {
2600       return error(f, STBVorbisError.invalid_stream);
2601     } else {
2602       Floor1* g = &f.floor_config[floor].floor1;
2603       if (get_bits!1(f)) {
2604         short* finalY;
2605         ubyte[256] step2_flag = void;
2606         immutable int[4] range_list = [ 256, 128, 86, 64 ];
2607         int range = range_list[g.floor1_multiplier-1];
2608         int offset = 2;
2609         finalY = f.finalY.ptr[i];
2610         finalY[0] = cast(short)get_bits_main(f, ilog(range)-1); //k8
2611         finalY[1] = cast(short)get_bits_main(f, ilog(range)-1); //k8
2612         foreach (immutable j; 0..g.partitions) {
2613           int pclass = g.partition_class_list.ptr[j];
2614           int cdim = g.class_dimensions.ptr[pclass];
2615           int cbits = g.class_subclasses.ptr[pclass];
2616           int csub = (1<<cbits)-1;
2617           int cval = 0;
2618           if (cbits) {
2619             Codebook *cc = f.codebooks+g.class_masterbooks.ptr[pclass];
2620             mixin(DECODE!("cval", "cc"));
2621           }
2622           foreach (immutable k; 0..cdim) {
2623             int book = g.subclass_books.ptr[pclass].ptr[cval&csub];
2624             cval = cval>>cbits;
2625             if (book >= 0) {
2626               int temp;
2627               Codebook *cc = f.codebooks+book;
2628               mixin(DECODE!("temp", "cc"));
2629               finalY[offset++] = cast(short)temp; //k8
2630             } else {
2631               finalY[offset++] = 0;
2632             }
2633           }
2634         }
2635         if (f.valid_bits == INVALID_BITS) goto error; // behavior according to spec
2636         step2_flag[0] = step2_flag[1] = 1;
2637         foreach (immutable j; 2..g.values) {
2638           int low = g.neighbors.ptr[j].ptr[0];
2639           int high = g.neighbors.ptr[j].ptr[1];
2640           //neighbors(g.xList, j, &low, &high);
2641           int pred = void;
2642           mixin(predict_point!(
2643             "pred", "g.xList.ptr[j]", "g.xList.ptr[low]", "g.xList.ptr[high]", "finalY[low]", "finalY[high]"
2644             )
2645           );
2646           int val = finalY[j];
2647           int highroom = range-pred;
2648           int lowroom = pred;
2649           auto room = (highroom < lowroom ? highroom : lowroom)*2;
2650           if (val) {
2651             step2_flag[low] = step2_flag[high] = 1;
2652             step2_flag[j] = 1;
2653             if (val >= room) {
2654               finalY[j] = cast(short)(highroom > lowroom ? val-lowroom+pred : pred-val+highroom-1); //k8
2655             } else {
2656               finalY[j] = cast(short)(val&1 ? pred-((val+1)>>1) : pred+(val>>1)); //k8
2657             }
2658           } else {
2659             step2_flag[j] = 0;
2660             finalY[j] = cast(short)pred; //k8
2661           }
2662         }
2663 
2664         version(STB_VORBIS_NO_DEFER_FLOOR) {
2665           // This is put here to turn off IDE warnings
2666           uint discardConsumer;
2667           discardConsumer = do_floor(f, map, i, n, f.floor_buffers.ptr[i], finalY, step2_flag);
2668         } else {
2669           // defer final floor computation until _after_ residue
2670           foreach (immutable j; 0..g.values) if (!step2_flag[j]) finalY[j] = -1;
2671         }
2672       } else {
2673   error:
2674         zero_channel[i] = true;
2675       }
2676       // So we just defer everything else to later
2677       // at this point we've decoded the floor into buffer
2678     }
2679   }
2680   //stb_prof(0);
2681   // at this point we've decoded all floors
2682 
2683   //debug(stb_vorbis) if (f.alloc.alloc_buffer) assert(f.alloc.alloc_buffer_length_in_bytes == f.temp_offset);
2684 
2685   // re-enable coupled channels if necessary
2686   memcpy(really_zero_channel.ptr, zero_channel.ptr, (really_zero_channel[0]).sizeof*f.vrchannels);
2687   foreach (immutable i; 0..map.coupling_steps) {
2688     if (!zero_channel[map.chan[i].magnitude] || !zero_channel[map.chan[i].angle]) {
2689       zero_channel[map.chan[i].magnitude] = zero_channel[map.chan[i].angle] = false;
2690     }
2691   }
2692 
2693   // RESIDUE DECODE
2694   foreach (immutable i; 0..map.submaps) {
2695     float*[STB_VORBIS_MAX_CHANNELS] residue_buffers;
2696     ubyte[256] do_not_decode = void;
2697     int ch = 0;
2698     foreach (immutable j; 0..f.vrchannels) {
2699       if (map.chan[j].mux == i) {
2700         if (zero_channel[j]) {
2701           do_not_decode[ch] = true;
2702           residue_buffers.ptr[ch] = null;
2703         } else {
2704           do_not_decode[ch] = false;
2705           residue_buffers.ptr[ch] = f.channel_buffers.ptr[j];
2706         }
2707         ++ch;
2708       }
2709     }
2710     int r = map.submap_residue.ptr[i];
2711     decode_residue(f, residue_buffers, ch, n2, r, do_not_decode.ptr);
2712   }
2713 
2714   //debug(stb_vorbis) if (f.alloc.alloc_buffer) assert(f.alloc.alloc_buffer_length_in_bytes == f.temp_offset);
2715 
2716    // INVERSE COUPLING
2717   //stb_prof(14);
2718   foreach_reverse (immutable i; 0..map.coupling_steps) {
2719     int n2n = n>>1;
2720     float* mm = f.channel_buffers.ptr[map.chan[i].magnitude];
2721     float* a = f.channel_buffers.ptr[map.chan[i].angle];
2722     foreach (immutable j; 0..n2n) {
2723       float a2, m2;
2724       if (mm[j] > 0) {
2725         if (a[j] > 0) { m2 = mm[j]; a2 = mm[j]-a[j]; } else { a2 = mm[j]; m2 = mm[j]+a[j]; }
2726       } else {
2727         if (a[j] > 0) { m2 = mm[j]; a2 = mm[j]+a[j]; } else { a2 = mm[j]; m2 = mm[j]-a[j]; }
2728       }
2729       mm[j] = m2;
2730       a[j] = a2;
2731     }
2732   }
2733 
2734   // finish decoding the floors
2735   version(STB_VORBIS_NO_DEFER_FLOOR) {
2736     foreach (immutable i; 0..f.vrchannels) {
2737       if (really_zero_channel[i]) {
2738         memset(f.channel_buffers.ptr[i], 0, (*f.channel_buffers.ptr[i]).sizeof*n2);
2739       } else {
2740         foreach (immutable j; 0..n2) f.channel_buffers.ptr[i].ptr[j] *= f.floor_buffers.ptr[i].ptr[j];
2741       }
2742     }
2743   } else {
2744     //stb_prof(15);
2745     foreach (immutable i; 0..f.vrchannels) {
2746       if (really_zero_channel[i]) {
2747         memset(f.channel_buffers.ptr[i], 0, (*f.channel_buffers.ptr[i]).sizeof*n2);
2748       } else {
2749         // This is put here to turn off IDE warnings
2750         uint discardConsumer;
2751         discardConsumer = do_floor(f, map, i, n, f.channel_buffers.ptr[i], f.finalY.ptr[i], null);
2752       }
2753     }
2754   }
2755 
2756   // INVERSE MDCT
2757   //stb_prof(16);
2758   foreach (immutable i; 0..f.vrchannels) inverse_mdct(f.channel_buffers.ptr[i], n, f, m.blockflag);
2759   //stb_prof(0);
2760 
2761   // this shouldn't be necessary, unless we exited on an error
2762   // and want to flush to get to the next packet
2763   flush_packet(f);
2764 
2765   if (f.first_decode) {
2766     // assume we start so first non-discarded sample is sample 0
2767     // this isn't to spec, but spec would require us to read ahead
2768     // and decode the size of all current frames--could be done,
2769     // but presumably it's not a commonly used feature
2770     f.current_loc = -n2; // start of first frame is positioned for discard
2771     // we might have to discard samples "from" the next frame too,
2772     // if we're lapping a large block then a small at the start?
2773     f.discard_samples_deferred = n-right_end;
2774     f.current_loc_valid = true;
2775     f.first_decode = false;
2776   } else if (f.discard_samples_deferred) {
2777     if (f.discard_samples_deferred >= right_start-left_start) {
2778       f.discard_samples_deferred -= (right_start-left_start);
2779       left_start = right_start;
2780       *p_left = left_start;
2781     } else {
2782       left_start += f.discard_samples_deferred;
2783       *p_left = left_start;
2784       f.discard_samples_deferred = 0;
2785     }
2786   } else if (f.previous_length == 0 && f.current_loc_valid) {
2787     // we're recovering from a seek... that means we're going to discard
2788     // the samples from this packet even though we know our position from
2789     // the last page header, so we need to update the position based on
2790     // the discarded samples here
2791     // but wait, the code below is going to add this in itself even
2792     // on a discard, so we don't need to do it here...
2793   }
2794 
2795   // check if we have ogg information about the sample # for this packet
2796   if (f.last_seg_which == f.end_seg_with_known_loc) {
2797     // if we have a valid current loc, and this is final:
2798     if (f.current_loc_valid && (f.page_flag&PAGEFLAG_last_page)) {
2799       uint current_end = f.known_loc_for_packet-(n-right_end);
2800       // then let's infer the size of the (probably) short final frame
2801       if (current_end < f.current_loc+right_end) {
2802         if (current_end < f.current_loc+(right_end-left_start)) {
2803           // negative truncation, that's impossible!
2804           *len = 0;
2805         } else {
2806           *len = current_end-f.current_loc;
2807         }
2808         *len += left_start;
2809         if (*len > right_end) *len = right_end; // this should never happen
2810         f.current_loc += *len;
2811         return true;
2812       }
2813     }
2814     // otherwise, just set our sample loc
2815     // guess that the ogg granule pos refers to the _middle_ of the
2816     // last frame?
2817     // set f.current_loc to the position of left_start
2818     f.current_loc = f.known_loc_for_packet-(n2-left_start);
2819     f.current_loc_valid = true;
2820   }
2821   if (f.current_loc_valid) f.current_loc += (right_start-left_start);
2822 
2823   //debug(stb_vorbis) if (f.alloc.alloc_buffer) assert(f.alloc.alloc_buffer_length_in_bytes == f.temp_offset);
2824 
2825   *len = right_end;  // ignore samples after the window goes to 0
2826   return true;
2827 }
2828 
2829 int vorbis_decode_packet (VorbisDecoder* f, int* len, int* p_left, int* p_right) {
2830   int mode, left_end, right_end;
2831   if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
2832   return vorbis_decode_packet_rest(f, len, f.mode_config.ptr+mode, *p_left, left_end, *p_right, right_end, p_left);
2833 }
2834 
2835 int vorbis_finish_frame (VorbisDecoder* f, int len, int left, int right) {
2836   // we use right&left (the start of the right- and left-window sin()-regions)
2837   // to determine how much to return, rather than inferring from the rules
2838   // (same result, clearer code); 'left' indicates where our sin() window
2839   // starts, therefore where the previous window's right edge starts, and
2840   // therefore where to start mixing from the previous buffer. 'right'
2841   // indicates where our sin() ending-window starts, therefore that's where
2842   // we start saving, and where our returned-data ends.
2843 
2844   // mixin from previous window
2845   if (f.previous_length) {
2846     int n = f.previous_length;
2847     float *w = get_window(f, n);
2848     foreach (immutable i; 0..f.vrchannels) {
2849       foreach (immutable j; 0..n) {
2850         (f.channel_buffers.ptr[i])[left+j] =
2851           (f.channel_buffers.ptr[i])[left+j]*w[    j]+
2852           (f.previous_window.ptr[i])[     j]*w[n-1-j];
2853       }
2854     }
2855   }
2856 
2857   auto prev = f.previous_length;
2858 
2859   // last half of this data becomes previous window
2860   f.previous_length = len-right;
2861 
2862   // @OPTIMIZE: could avoid this copy by double-buffering the
2863   // output (flipping previous_window with channel_buffers), but
2864   // then previous_window would have to be 2x as large, and
2865   // channel_buffers couldn't be temp mem (although they're NOT
2866   // currently temp mem, they could be (unless we want to level
2867   // performance by spreading out the computation))
2868   foreach (immutable i; 0..f.vrchannels) {
2869     for (uint j = 0; right+j < len; ++j) (f.previous_window.ptr[i])[j] = (f.channel_buffers.ptr[i])[right+j];
2870   }
2871 
2872   if (!prev) {
2873     // there was no previous packet, so this data isn't valid...
2874     // this isn't entirely true, only the would-have-overlapped data
2875     // isn't valid, but this seems to be what the spec requires
2876     return 0;
2877   }
2878 
2879   // truncate a short frame
2880   if (len < right) right = len;
2881 
2882   f.samples_output += right-left;
2883 
2884   return right-left;
2885 }
2886 
2887 bool vorbis_pump_first_frame (VorbisDecoder* f) {
2888   int len, right, left;
2889   if (vorbis_decode_packet(f, &len, &left, &right)) {
2890     // This is put here to turn off IDE warnings
2891     uint discardConsumer;
2892     discardConsumer = vorbis_finish_frame(f, len, left, right);
2893     return true;
2894   }
2895   return false;
2896 }
2897 
2898 /+ k8: i don't need that, so it's dead
2899 int is_whole_packet_present (VorbisDecoder* f, int end_page) {
2900   import core.stdc.string : memcmp;
2901 
2902   // make sure that we have the packet available before continuing...
2903   // this requires a full ogg parse, but we know we can fetch from f.stream
2904 
2905   // instead of coding this out explicitly, we could save the current read state,
2906   // read the next packet with get8() until end-of-packet, check f.eof, then
2907   // reset the state? but that would be slower, esp. since we'd have over 256 bytes
2908   // of state to restore (primarily the page segment table)
2909 
2910   int s = f.next_seg, first = true;
2911   ubyte *p = f.stream;
2912 
2913   if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
2914     for (; s < f.segment_count; ++s) {
2915       p += f.segments[s];
2916       if (f.segments[s] < 255) break; // stop at first short segment
2917     }
2918     // either this continues, or it ends it...
2919     if (end_page && s < f.segment_count-1) return error(f, STBVorbisError.invalid_stream);
2920     if (s == f.segment_count) s = -1; // set 'crosses page' flag
2921     if (p > f.stream_end) return error(f, STBVorbisError.need_more_data);
2922     first = false;
2923   }
2924   while (s == -1) {
2925     ubyte* q = void;
2926     int n = void;
2927     // check that we have the page header ready
2928     if (p+26 >= f.stream_end) return error(f, STBVorbisError.need_more_data);
2929     // validate the page
2930     if (memcmp(p, ogg_page_header.ptr, 4)) return error(f, STBVorbisError.invalid_stream);
2931     if (p[4] != 0) return error(f, STBVorbisError.invalid_stream);
2932     if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
2933       if (f.previous_length && (p[5]&PAGEFLAG_continued_packet)) return error(f, STBVorbisError.invalid_stream);
2934       // if no previous length, we're resynching, so we can come in on a continued-packet,
2935       // which we'll just drop
2936     } else {
2937       if (!(p[5]&PAGEFLAG_continued_packet)) return error(f, STBVorbisError.invalid_stream);
2938     }
2939     n = p[26]; // segment counts
2940     q = p+27; // q points to segment table
2941     p = q+n; // advance past header
2942     // make sure we've read the segment table
2943     if (p > f.stream_end) return error(f, STBVorbisError.need_more_data);
2944     for (s = 0; s < n; ++s) {
2945       p += q[s];
2946       if (q[s] < 255) break;
2947     }
2948     if (end_page && s < n-1) return error(f, STBVorbisError.invalid_stream);
2949     if (s == n) s = -1; // set 'crosses page' flag
2950     if (p > f.stream_end) return error(f, STBVorbisError.need_more_data);
2951     first = false;
2952   }
2953   return true;
2954 }
2955 +/
2956 
2957 int start_decoder (VorbisDecoder* f) {
2958   import core.stdc.string : memcpy, memset;
2959   ubyte[6] header;
2960   ubyte x, y;
2961   int len, max_submaps = 0;
2962   int longest_floorlist = 0;
2963 
2964   // first page, first packet
2965 
2966   if (!start_page(f)) return false;
2967   // validate page flag
2968   if (!(f.page_flag&PAGEFLAG_first_page)) return error(f, STBVorbisError.invalid_first_page);
2969   if (f.page_flag&PAGEFLAG_last_page) return error(f, STBVorbisError.invalid_first_page);
2970   if (f.page_flag&PAGEFLAG_continued_packet) return error(f, STBVorbisError.invalid_first_page);
2971   // check for expected packet length
2972   if (f.segment_count != 1) return error(f, STBVorbisError.invalid_first_page);
2973   if (f.segments[0] != 30) return error(f, STBVorbisError.invalid_first_page);
2974   // read packet
2975   // check packet header
2976   if (get8(f) != VorbisPacket.id) return error(f, STBVorbisError.invalid_first_page);
2977   if (!getn(f, header.ptr, 6)) return error(f, STBVorbisError.unexpected_eof);
2978   if (!vorbis_validate(header.ptr)) return error(f, STBVorbisError.invalid_first_page);
2979   // vorbis_version
2980   if (get32(f) != 0) return error(f, STBVorbisError.invalid_first_page);
2981   f.vrchannels = get8(f); if (!f.vrchannels) return error(f, STBVorbisError.invalid_first_page);
2982   if (f.vrchannels > STB_VORBIS_MAX_CHANNELS) return error(f, STBVorbisError.too_many_channels);
2983   f.sample_rate = get32(f); if (!f.sample_rate) return error(f, STBVorbisError.invalid_first_page);
2984   // This is put here to turn off IDE warnings
2985   uint discardConsumer;
2986   discardConsumer = get32(f); // bitrate_maximum
2987   discardConsumer = get32(f); // bitrate_nominal
2988   discardConsumer = get32(f); // bitrate_minimum
2989   x = get8(f);
2990   {
2991     int log0 = x&15;
2992     int log1 = x>>4;
2993     f.blocksize_0 = 1<<log0;
2994     f.blocksize_1 = 1<<log1;
2995     if (log0 < 6 || log0 > 13) return error(f, STBVorbisError.invalid_setup);
2996     if (log1 < 6 || log1 > 13) return error(f, STBVorbisError.invalid_setup);
2997     if (log0 > log1) return error(f, STBVorbisError.invalid_setup);
2998   }
2999 
3000   // framing_flag
3001   x = get8(f);
3002   if (!(x&1)) return error(f, STBVorbisError.invalid_first_page);
3003 
3004   // second packet! (comments)
3005   if (!start_page(f)) return false;
3006 
3007   // read comments
3008   if (!start_packet(f)) return false;
3009 
3010   if (f.read_comments) {
3011     /+if (f.push_mode) {
3012       if (!is_whole_packet_present(f, true)) {
3013         // convert error in ogg header to write type
3014         if (f.error == STBVorbisError.invalid_stream) f.error = STBVorbisError.invalid_setup;
3015         return false;
3016       }
3017     }+/
3018     if (get8_packet(f) != VorbisPacket.comment) return error(f, STBVorbisError.invalid_setup);
3019     foreach (immutable i; 0..6) header[i] = cast(ubyte)get8_packet(f); //k8
3020     if (!vorbis_validate(header.ptr)) return error(f, STBVorbisError.invalid_setup);
3021 
3022     // skip vendor id
3023     uint vidsize = get32_packet(f);
3024     //{ import core.stdc.stdio; printf("vendor size: %u\n", vidsize); }
3025     if (vidsize == EOP) return error(f, STBVorbisError.invalid_setup);
3026     // This is put here to turn off IDE warnings
3027     while (vidsize--)
3028         discardConsumer = get8_packet(f);
3029 
3030     // read comments section
3031     uint cmtcount = get32_packet(f);
3032     if (cmtcount == EOP) return error(f, STBVorbisError.invalid_setup);
3033     if (cmtcount > 0) {
3034       uint cmtsize = 32_768; // this should be enough for everyone
3035       f.comment_data = setup_malloc!ubyte(f, cmtsize);
3036       if (f.comment_data is null) return error(f, STBVorbisError.outofmem);
3037       auto cmtpos = 0;
3038       auto d = f.comment_data;
3039       while (cmtcount--) {
3040         uint linelen = get32_packet(f);
3041         //{ import core.stdc.stdio; printf("linelen: %u; lines left: %u\n", linelen, cmtcount); }
3042         if (linelen == EOP || linelen > ushort.max-2) break;
3043         if (linelen == 0) { continue; }
3044         if (cmtpos+2+linelen > cmtsize) break;
3045         cmtpos += linelen+2;
3046         *d++ = (linelen+2)&0xff;
3047         *d++ = ((linelen+2)>>8)&0xff;
3048         while (linelen--) {
3049           auto b = get8_packet(f);
3050           if (b == EOP) return error(f, STBVorbisError.outofmem);
3051           *d++ = cast(ubyte)b;
3052         }
3053         //{ import core.stdc.stdio; printf("%u bytes of comments read\n", cmtpos); }
3054         f.comment_size = cmtpos;
3055       }
3056     }
3057     flush_packet(f);
3058     f.comment_rewind();    
3059   } else {
3060     // skip comments
3061     do {
3062       len = next_segment(f);
3063       skip(f, len);
3064       f.bytes_in_seg = 0;
3065     } while (len);
3066   }
3067 
3068   // third packet!
3069   if (!start_packet(f)) return false;
3070 
3071   /+if (f.push_mode) {
3072     if (!is_whole_packet_present(f, true)) {
3073       // convert error in ogg header to write type
3074       if (f.error == STBVorbisError.invalid_stream) f.error = STBVorbisError.invalid_setup;
3075       return false;
3076     }
3077   }+/
3078 
3079   if (get8_packet(f) != VorbisPacket.setup) return error(f, STBVorbisError.invalid_setup);
3080   foreach (immutable i; 0..6) header[i] = cast(ubyte)get8_packet(f); //k8
3081   if (!vorbis_validate(header.ptr)) return error(f, STBVorbisError.invalid_setup);
3082 
3083   // codebooks
3084   f.codebook_count = get_bits!8(f)+1;
3085   f.codebooks = setup_malloc!Codebook(f, f.codebook_count);
3086   static assert((*f.codebooks).sizeof == Codebook.sizeof);
3087   if (f.codebooks is null) return error(f, STBVorbisError.outofmem);
3088   memset(f.codebooks, 0, (*f.codebooks).sizeof*f.codebook_count);
3089 
3090   foreach (immutable i; 0..f.codebook_count) {
3091 
3092     uint* values;
3093     int ordered, sorted_count;
3094     int total = 0;
3095     ubyte* lengths;
3096     Codebook* c = f.codebooks+i;
3097     x = get_bits!8(f);
3098     if (x != 0x42)
3099         return error(f, STBVorbisError.invalid_setup);
3100     
3101     x = get_bits!8(f); if (x != 0x43) return error(f, STBVorbisError.invalid_setup);
3102     x = get_bits!8(f); if (x != 0x56) return error(f, STBVorbisError.invalid_setup);
3103     x = get_bits!8(f);
3104     c.dimensions = (get_bits!8(f)<<8)+x;
3105     x = get_bits!8(f);
3106     y = get_bits!8(f);
3107     c.entries = (get_bits!8(f)<<16)+(y<<8)+x;
3108     ordered = get_bits!1(f);
3109     c.sparse = (ordered ? 0 : get_bits!1(f));
3110 
3111 
3112     if (c.dimensions == 0 && c.entries != 0) return error(f, STBVorbisError.invalid_setup);
3113 
3114     if (c.sparse) {
3115       lengths = cast(ubyte*)setup_temp_malloc(f, c.entries);
3116     } else {
3117       lengths = c.codeword_lengths = setup_malloc!ubyte(f, c.entries);
3118     }
3119 
3120     if (lengths is null) return error(f, STBVorbisError.outofmem);
3121 
3122     if (ordered) {
3123       int current_entry = 0;
3124       int current_length = get_bits_add_no!5(f, 1);
3125       while (current_entry < c.entries) {
3126         int limit = c.entries-current_entry;
3127         int n = get_bits_main(f, ilog(limit));
3128         if (current_entry+n > cast(int)c.entries) return error(f, STBVorbisError.invalid_setup);
3129         memset(lengths+current_entry, current_length, n);
3130         current_entry += n;
3131         ++current_length;
3132       }
3133     } else {
3134       foreach (immutable j; 0..c.entries) {
3135         int present = (c.sparse ? get_bits!1(f) : 1);
3136         if (present) {
3137           lengths[j] = get_bits_add_no!5(f, 1);
3138           ++total;
3139           if (lengths[j] == 32) return error(f, STBVorbisError.invalid_setup);
3140         } else {
3141           lengths[j] = NO_CODE;
3142         }
3143       }
3144     }
3145 
3146 
3147     if (c.sparse && total >= c.entries>>2) {
3148       // convert sparse items to non-sparse!
3149       if (c.entries > cast(int)f.setup_temp_memory_required) f.setup_temp_memory_required = c.entries;
3150       c.codeword_lengths = setup_malloc!ubyte(f, c.entries);
3151       if (c.codeword_lengths is null) return error(f, STBVorbisError.outofmem);
3152       memcpy(c.codeword_lengths, lengths, c.entries);
3153       setup_temp_free(f, lengths, c.entries); // note this is only safe if there have been no intervening temp mallocs!
3154       lengths = c.codeword_lengths;
3155       c.sparse = 0;
3156     }
3157 
3158     // compute the size of the sorted tables
3159     if (c.sparse) {
3160       sorted_count = total;
3161     } else {
3162       sorted_count = 0;
3163       version(STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH) {} else {
3164         foreach (immutable j; 0..c.entries)
3165             if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count;
3166       }
3167     }
3168 
3169     c.sorted_entries = sorted_count;
3170     values = null;
3171 
3172     if (!c.sparse) {
3173       c.codewords = setup_malloc!uint(f, c.entries);
3174       if (!c.codewords) return error(f, STBVorbisError.outofmem);
3175     } else {
3176       if (c.sorted_entries) {
3177         c.codeword_lengths = setup_malloc!ubyte(f, c.sorted_entries);
3178         if (!c.codeword_lengths) return error(f, STBVorbisError.outofmem);
3179         c.codewords = cast(uint*)setup_temp_malloc(f, cast(int)(*c.codewords).sizeof*c.sorted_entries);
3180         if (!c.codewords) return error(f, STBVorbisError.outofmem);
3181         values = cast(uint*)setup_temp_malloc(f, cast(int)(*values).sizeof*c.sorted_entries);
3182         if (!values) return error(f, STBVorbisError.outofmem);
3183       }
3184       uint size = c.entries+cast(int)((*c.codewords).sizeof+(*values).sizeof)*c.sorted_entries;
3185       if (size > f.setup_temp_memory_required) f.setup_temp_memory_required = size;
3186     }
3187 
3188     if (!compute_codewords(c, lengths, c.entries, values)) {
3189       if (c.sparse) setup_temp_free(f, values, 0);
3190       return error(f, STBVorbisError.invalid_setup);
3191     }
3192 
3193     if (c.sorted_entries) {
3194       // allocate an extra slot for sentinels
3195       c.sorted_codewords = setup_malloc!uint(f, c.sorted_entries+1);
3196       if (c.sorted_codewords is null) return error(f, STBVorbisError.outofmem);
3197       // allocate an extra slot at the front so that c.sorted_values[-1] is defined
3198       // so that we can catch that case without an extra if
3199       c.sorted_values = setup_malloc!int(f, c.sorted_entries+1);
3200       if (c.sorted_values is null) return error(f, STBVorbisError.outofmem);
3201       ++c.sorted_values;
3202       c.sorted_values[-1] = -1;
3203       compute_sorted_huffman(c, lengths, values);
3204     }
3205 
3206     if (c.sparse) {
3207       setup_temp_free(f, values, cast(int)(*values).sizeof*c.sorted_entries);
3208       setup_temp_free(f, c.codewords, cast(int)(*c.codewords).sizeof*c.sorted_entries);
3209       setup_temp_free(f, lengths, c.entries);
3210       c.codewords = null;
3211     }
3212 
3213     
3214     compute_accelerated_huffman(c);
3215 
3216     c.lookup_type = get_bits!4(f);
3217     if (c.lookup_type > 2) return error(f, STBVorbisError.invalid_setup);
3218     if (c.lookup_type > 0) {
3219       ushort* mults;
3220       c.minimum_value = float32_unpack(get_bits!32(f));
3221       c.delta_value = float32_unpack(get_bits!32(f));
3222       c.value_bits = get_bits_add_no!4(f, 1);
3223       c.sequence_p = get_bits!1(f);
3224       if (c.lookup_type == 1) {
3225         c.lookup_values = lookup1_values(c.entries, c.dimensions);
3226       } else {
3227         c.lookup_values = c.entries*c.dimensions;
3228       }
3229       if (c.lookup_values == 0) return error(f, STBVorbisError.invalid_setup);
3230       mults = cast(ushort*)setup_temp_malloc(f, cast(int)(mults[0]).sizeof*c.lookup_values);
3231       if (mults is null) return error(f, STBVorbisError.outofmem);
3232       foreach (immutable j; 0..cast(int)c.lookup_values) {
3233         int q = get_bits_main(f, c.value_bits);
3234         if (q == EOP) { setup_temp_free(f, mults, cast(int)(mults[0]).sizeof*c.lookup_values);
3235             return error(f, STBVorbisError.invalid_setup);
3236         }
3237         mults[j] = cast(ushort)q; //k8
3238       }
3239 
3240       version(STB_VORBIS_DIVIDES_IN_CODEBOOK) {} else {
3241         if (c.lookup_type == 1) {
3242           int sparse = c.sparse; //len
3243           float last = 0;
3244           // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
3245           if (sparse) {
3246             if (c.sorted_entries == 0) goto skip;
3247             c.multiplicands = setup_malloc!codetype(f, c.sorted_entries*c.dimensions);
3248           } else {
3249             c.multiplicands = setup_malloc!codetype(f, c.entries*c.dimensions);
3250           }
3251           if (c.multiplicands is null) {
3252             setup_temp_free(f, mults, cast(int)(mults[0]).sizeof*c.lookup_values);
3253             return error(f, STBVorbisError.outofmem);
3254           }
3255           foreach (immutable j; 0..(sparse ? c.sorted_entries : c.entries)) {
3256             uint z = (sparse ? c.sorted_values[j] : j);
3257             uint div = 1;
3258             foreach (immutable k; 0..c.dimensions) {
3259               int off = (z/div)%c.lookup_values;
3260               float val = mults[off];
3261               val = val*c.delta_value+c.minimum_value+last;
3262               c.multiplicands[j*c.dimensions+k] = val;
3263               if (c.sequence_p) last = val;
3264               if (k+1 < c.dimensions) {
3265                  if (div > uint.max/cast(uint)c.lookup_values) {
3266                     setup_temp_free(f, mults, cast(uint)(mults[0]).sizeof*c.lookup_values);
3267                     return error(f, STBVorbisError.invalid_setup);
3268                  }
3269                  div *= c.lookup_values;
3270               }
3271             }
3272           }
3273           c.lookup_type = 2;
3274           goto skip;
3275         }
3276         //else
3277       }
3278       {
3279         float last = 0;
3280         c.multiplicands = setup_malloc!codetype(f, c.lookup_values);
3281         if (c.multiplicands is null) {
3282             setup_temp_free(f, mults, cast(uint)(mults[0]).sizeof*c.lookup_values);
3283             return error(f, STBVorbisError.outofmem);
3284         }
3285         foreach (immutable j; 0..cast(int)c.lookup_values) {
3286           float val = mults[j]*c.delta_value+c.minimum_value+last;
3287           c.multiplicands[j] = val;
3288           if (c.sequence_p) last = val;
3289         }
3290       }
3291      //version(STB_VORBIS_DIVIDES_IN_CODEBOOK)
3292      skip: // this is versioned out in C
3293       setup_temp_free(f, mults, cast(uint)(mults[0]).sizeof*c.lookup_values);
3294     }
3295   }
3296 
3297   // time domain transfers (notused)
3298   x = get_bits_add_no!6(f, 1);
3299   foreach (immutable i; 0..x) {
3300     auto z = get_bits!16(f);
3301     if (z != 0) return error(f, STBVorbisError.invalid_setup);
3302   }
3303 
3304   // Floors
3305   f.floor_count = get_bits_add_no!6(f, 1);
3306   f.floor_config = setup_malloc!Floor(f, f.floor_count);
3307   if (f.floor_config is null) return error(f, STBVorbisError.outofmem);
3308   foreach (immutable i; 0..f.floor_count) {
3309     f.floor_types[i] = get_bits!16(f);
3310     if (f.floor_types[i] > 1) return error(f, STBVorbisError.invalid_setup);
3311     if (f.floor_types[i] == 0) {
3312       Floor0* g = &f.floor_config[i].floor0;
3313       g.order = get_bits!8(f);
3314       g.rate = get_bits!16(f);
3315       g.bark_map_size = get_bits!16(f);
3316       g.amplitude_bits = get_bits!6(f);
3317       g.amplitude_offset = get_bits!8(f);
3318       g.number_of_books = get_bits_add_no!4(f, 1);
3319       foreach (immutable j; 0..g.number_of_books) g.book_list[j] = get_bits!8(f);
3320       return error(f, STBVorbisError.feature_not_supported);
3321     } else {
3322       Point[31*8+2] p;
3323       Floor1 *g = &f.floor_config[i].floor1;
3324       int max_class = -1;
3325       g.partitions = get_bits!5(f);
3326       foreach (immutable j; 0..g.partitions) {
3327         g.partition_class_list[j] = get_bits!4(f);
3328         if (g.partition_class_list[j] > max_class) max_class = g.partition_class_list[j];
3329       }
3330       foreach (immutable j; 0..max_class+1) {
3331         g.class_dimensions[j] = get_bits_add_no!3(f, 1);
3332         g.class_subclasses[j] = get_bits!2(f);
3333         if (g.class_subclasses[j]) {
3334           g.class_masterbooks[j] = get_bits!8(f);
3335           if (g.class_masterbooks[j] >= f.codebook_count) return error(f, STBVorbisError.invalid_setup);
3336         }
3337         foreach (immutable k; 0..1<<g.class_subclasses[j]) {
3338           g.subclass_books[j].ptr[k] = get_bits!8(f)-1;
3339           if (g.subclass_books[j].ptr[k] >= f.codebook_count) return error(f, STBVorbisError.invalid_setup);
3340         }
3341       }
3342       g.floor1_multiplier = get_bits_add_no!2(f, 1);
3343       g.rangebits = get_bits!4(f);
3344       g.xList[0] = 0;
3345       g.xList[1] = cast(ushort)(1<<g.rangebits); //k8
3346       g.values = 2;
3347       foreach (immutable j; 0..g.partitions) {
3348         int c = g.partition_class_list[j];
3349         foreach (immutable k; 0..g.class_dimensions[c]) {
3350           g.xList[g.values] = cast(ushort)get_bits_main(f, g.rangebits); //k8
3351           ++g.values;
3352         }
3353       }
3354       assert(g.values <= ushort.max);
3355       // precompute the sorting
3356       foreach (ushort j; 0..cast(ushort)g.values) {
3357         p[j].x = g.xList[j];
3358         p[j].y = j;
3359       }
3360       qsort(p.ptr, g.values, (p[0]).sizeof, &point_compare);
3361       foreach (uint j; 0..g.values) g.sorted_order.ptr[j] = cast(ubyte)p.ptr[j].y;
3362       // precompute the neighbors
3363       foreach (uint j; 2..g.values) {
3364         ushort low = void, hi = void;
3365         neighbors(g.xList.ptr, j, &low, &hi);
3366         assert(low <= ubyte.max);
3367         assert(hi <= ubyte.max);
3368         g.neighbors[j].ptr[0] = cast(ubyte)low;
3369         g.neighbors[j].ptr[1] = cast(ubyte)hi;
3370       }
3371       if (g.values > longest_floorlist) longest_floorlist = g.values;
3372     }
3373   }
3374 
3375   // Residue
3376   f.residue_count = get_bits_add_no!6(f, 1);
3377   f.residue_config = setup_malloc!Residue(f, f.residue_count);
3378   if (f.residue_config is null) return error(f, STBVorbisError.outofmem);
3379   memset(f.residue_config, 0, f.residue_count*(f.residue_config[0]).sizeof);
3380   foreach (immutable i; 0..f.residue_count) {
3381     ubyte[64] residue_cascade;
3382     Residue* r = f.residue_config+i;
3383     f.residue_types[i] = get_bits!16(f);
3384     if (f.residue_types[i] > 2) return error(f, STBVorbisError.invalid_setup);
3385     r.begin = get_bits!24(f);
3386     r.end = get_bits!24(f);
3387     if (r.end < r.begin) return error(f, STBVorbisError.invalid_setup);
3388     r.part_size = get_bits_add_no!24(f, 1);
3389     r.classifications = get_bits_add_no!6(f, 1);
3390     r.classbook = get_bits!8(f);
3391     if (r.classbook >= f.codebook_count) return error(f, STBVorbisError.invalid_setup);
3392     foreach (immutable j; 0..r.classifications) {
3393       ubyte high_bits = 0;
3394       ubyte low_bits = get_bits!3(f);
3395       if (get_bits!1(f)) high_bits = get_bits!5(f);
3396       assert(high_bits*8+low_bits <= ubyte.max);
3397       residue_cascade[j] = cast(ubyte)(high_bits*8+low_bits);
3398     }
3399     static assert(r.residue_books[0].sizeof == 16);
3400     r.residue_books = setup_malloc!(short[8])(f, r.classifications);
3401     if (r.residue_books is null) return error(f, STBVorbisError.outofmem);
3402     foreach (immutable j; 0..r.classifications) {
3403       foreach (immutable k; 0..8) {
3404         if (residue_cascade[j]&(1<<k)) {
3405           r.residue_books[j].ptr[k] = get_bits!8(f);
3406           if (r.residue_books[j].ptr[k] >= f.codebook_count) return error(f, STBVorbisError.invalid_setup);
3407         } else {
3408           r.residue_books[j].ptr[k] = -1;
3409         }
3410       }
3411     }
3412     // precompute the classifications[] array to avoid inner-loop mod/divide
3413     // call it 'classdata' since we already have r.classifications
3414     r.classdata = setup_malloc!(ubyte*)(f, f.codebooks[r.classbook].entries);
3415     if (!r.classdata) return error(f, STBVorbisError.outofmem);
3416     memset(r.classdata, 0, (*r.classdata).sizeof*f.codebooks[r.classbook].entries);
3417     foreach (immutable j; 0..f.codebooks[r.classbook].entries) {
3418       int classwords = f.codebooks[r.classbook].dimensions;
3419       int temp = j;
3420       r.classdata[j] = setup_malloc!ubyte(f, classwords);
3421       if (r.classdata[j] is null) return error(f, STBVorbisError.outofmem);
3422       foreach_reverse (immutable k; 0..classwords) {
3423         assert(temp%r.classifications >= 0 && temp%r.classifications <= ubyte.max);
3424         r.classdata[j][k] = cast(ubyte)(temp%r.classifications);
3425         temp /= r.classifications;
3426       }
3427     }
3428   }
3429 
3430   f.mapping_count = get_bits_add_no!6(f, 1);
3431   f.mapping = setup_malloc!Mapping(f, f.mapping_count);
3432   if (f.mapping is null) return error(f, STBVorbisError.outofmem);
3433   memset(f.mapping, 0, f.mapping_count*(*f.mapping).sizeof);
3434   foreach (immutable i; 0..f.mapping_count) {
3435     Mapping* m = f.mapping+i;
3436     int mapping_type = get_bits!16(f);
3437     if (mapping_type != 0) return error(f, STBVorbisError.invalid_setup);
3438     m.chan = setup_malloc!MappingChannel(f, f.vrchannels);
3439     if (m.chan is null) return error(f, STBVorbisError.outofmem);
3440     m.submaps = (get_bits!1(f) ? get_bits_add_no!4(f, 1) : 1);
3441     if (m.submaps > max_submaps) max_submaps = m.submaps;
3442     if (get_bits!1(f)) {
3443       m.coupling_steps = get_bits_add_no!8(f, 1);
3444       foreach (immutable k; 0..m.coupling_steps) {
3445         m.chan[k].magnitude = cast(ubyte)get_bits_main(f, ilog(f.vrchannels-1)); //k8
3446         m.chan[k].angle = cast(ubyte)get_bits_main(f, ilog(f.vrchannels-1)); //k8
3447         if (m.chan[k].magnitude >= f.vrchannels) return error(f, STBVorbisError.invalid_setup);
3448         if (m.chan[k].angle     >= f.vrchannels) return error(f, STBVorbisError.invalid_setup);
3449         if (m.chan[k].magnitude == m.chan[k].angle) return error(f, STBVorbisError.invalid_setup);
3450       }
3451     } else {
3452       m.coupling_steps = 0;
3453     }
3454 
3455     // reserved field
3456     if (get_bits!2(f)) return error(f, STBVorbisError.invalid_setup);
3457     if (m.submaps > 1) {
3458       foreach (immutable j; 0..f.vrchannels) {
3459         m.chan[j].mux = get_bits!4(f);
3460         if (m.chan[j].mux >= m.submaps) return error(f, STBVorbisError.invalid_setup);
3461       }
3462     } else {
3463       // @SPECIFICATION: this case is missing from the spec
3464       foreach (immutable j; 0..f.vrchannels) m.chan[j].mux = 0;
3465     }
3466     foreach (immutable j; 0..m.submaps) {
3467       get_bits!8(f); // discard
3468       m.submap_floor[j] = get_bits!8(f);
3469       m.submap_residue[j] = get_bits!8(f);
3470       if (m.submap_floor[j] >= f.floor_count) return error(f, STBVorbisError.invalid_setup);
3471       if (m.submap_residue[j] >= f.residue_count) return error(f, STBVorbisError.invalid_setup);
3472     }
3473   }
3474 
3475   // Modes
3476   f.mode_count = get_bits_add_no!6(f, 1);
3477   foreach (immutable i; 0..f.mode_count) {
3478     Mode* m = f.mode_config.ptr+i;
3479     m.blockflag = get_bits!1(f);
3480     m.windowtype = get_bits!16(f);
3481     m.transformtype = get_bits!16(f);
3482     m.mapping = get_bits!8(f);
3483     if (m.windowtype != 0) return error(f, STBVorbisError.invalid_setup);
3484     if (m.transformtype != 0) return error(f, STBVorbisError.invalid_setup);
3485     if (m.mapping >= f.mapping_count) return error(f, STBVorbisError.invalid_setup);
3486   }
3487 
3488   flush_packet(f);
3489 
3490   f.previous_length = 0;
3491 
3492   foreach (immutable i; 0..f.vrchannels) {
3493     f.channel_buffers.ptr[i] = setup_malloc!float(f, f.blocksize_1);
3494     f.previous_window.ptr[i] = setup_malloc!float(f, f.blocksize_1/2);
3495     f.finalY.ptr[i]          = setup_malloc!short(f, longest_floorlist);
3496     if (f.channel_buffers.ptr[i] is null || f.previous_window.ptr[i] is null || f.finalY.ptr[i] is null)
3497         return error(f, STBVorbisError.outofmem);
3498     version(STB_VORBIS_NO_DEFER_FLOOR) {
3499       f.floor_buffers.ptr[i] = setup_malloc!float(f, f.blocksize_1/2);
3500       if (f.floor_buffers.ptr[i] is null) return error(f, STBVorbisError.outofmem);
3501     }
3502   }
3503 
3504   if (!init_blocksize(f, 0, f.blocksize_0)) return false;
3505   if (!init_blocksize(f, 1, f.blocksize_1)) return false;
3506   f.blocksize.ptr[0] = f.blocksize_0;
3507   f.blocksize.ptr[1] = f.blocksize_1;
3508 
3509   version(STB_VORBIS_DIVIDE_TABLE) {
3510     if (integer_divide_table[1].ptr[1] == 0) {
3511       foreach (immutable i; 0..DIVTAB_NUMER)
3512         foreach (immutable j; 1..DIVTAB_DENOM)
3513             integer_divide_table[i].ptr[j] = i/j;
3514     }
3515   }
3516 
3517   // compute how much temporary memory is needed
3518 
3519   // 1.
3520   {
3521     uint imdct_mem = (f.blocksize_1*cast(uint)(float).sizeof>>1);
3522     uint classify_mem;
3523     int max_part_read = 0;
3524     foreach (immutable i; 0..f.residue_count) {
3525       Residue* r = f.residue_config+i;
3526       int n_read = r.end-r.begin;
3527       int part_read = n_read/r.part_size;
3528       if (part_read > max_part_read) max_part_read = part_read;
3529     }
3530     version(STB_VORBIS_DIVIDES_IN_RESIDUE) {
3531       classify_mem = f.vrchannels*cast(uint)((void*).sizeof+max_part_read*(int*).sizeof);
3532     } else {
3533       classify_mem = f.vrchannels*cast(uint)((void*).sizeof+max_part_read*(ubyte*).sizeof);
3534     }
3535     f.temp_memory_required = classify_mem;
3536     if (imdct_mem > f.temp_memory_required) f.temp_memory_required = imdct_mem;
3537   }
3538 
3539   f.first_decode = true;
3540 
3541   /+
3542   if (f.alloc.alloc_buffer) {
3543     debug(stb_vorbis) assert(f.temp_offset == f.alloc.alloc_buffer_length_in_bytes);
3544     // check if there's enough temp memory so we don't error later
3545     if (f.setup_offset+ /*(*f).sizeof+*/ f.temp_memory_required > cast(uint)f.temp_offset) return error(f, STBVorbisError.outofmem);
3546   }
3547   +/
3548 
3549   f.first_audio_page_offset = f.fileOffset();
3550 
3551   return true;
3552 }
3553 
3554 /+
3555 int vorbis_search_for_page_pushdata (VorbisDecoder* f, ubyte* data, int data_len) {
3556   import core.stdc.string : memcmp;
3557 
3558   foreach (immutable i; 0..f.page_crc_tests) f.scan.ptr[i].bytes_done = 0;
3559 
3560   // if we have room for more scans, search for them first, because
3561   // they may cause us to stop early if their header is incomplete
3562   if (f.page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
3563     if (data_len < 4) return 0;
3564     data_len -= 3; // need to look for 4-byte sequence, so don't miss one that straddles a boundary
3565     foreach (immutable i; 0..data_len) {
3566       if (data[i] == 0x4f) {
3567         if (memcmp(data+i, ogg_page_header.ptr, 4) == 0) {
3568           // make sure we have the whole page header
3569           if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
3570             // only read up to this page start, so hopefully we'll
3571             // have the whole page header start next time
3572             data_len = i;
3573             break;
3574           }
3575           // ok, we have it all; compute the length of the page
3576           auto len = 27+data[i+26];
3577           foreach (immutable j; 0..data[i+26]) len += data[i+27+j];
3578           // scan everything up to the embedded crc (which we must 0)
3579           uint crc = 0;
3580           foreach (immutable j; 0..22) crc = crc32_update(crc, data[i+j]);
3581           // now process 4 0-bytes
3582           foreach (immutable j; 22..26) crc = crc32_update(crc, 0);
3583           // len is the total number of bytes we need to scan
3584           auto n = f.page_crc_tests++;
3585           f.scan.ptr[n].bytes_left = len-/*j*/26;
3586           f.scan.ptr[n].crc_so_far = crc;
3587           f.scan.ptr[n].goal_crc = data[i+22]+(data[i+23]<<8)+(data[i+24]<<16)+(data[i+25]<<24);
3588           // if the last frame on a page is continued to the next, then
3589           // we can't recover the sample_loc immediately
3590           if (data[i+27+data[i+26]-1] == 255) {
3591             f.scan.ptr[n].sample_loc = ~0;
3592           } else {
3593             f.scan.ptr[n].sample_loc = data[i+6]+(data[i+7]<<8)+(data[i+8]<<16)+(data[i+9]<<24);
3594           }
3595           f.scan.ptr[n].bytes_done = i+26/*j*/;
3596           if (f.page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break;
3597           // keep going if we still have room for more
3598         }
3599       }
3600     }
3601   }
3602 
3603   for (uint i = 0; i < f.page_crc_tests; ) {
3604     int nn = f.scan.ptr[i].bytes_done;
3605     int m = f.scan.ptr[i].bytes_left;
3606     if (m > data_len-nn) m = data_len-nn;
3607     // m is the bytes to scan in the current chunk
3608     uint crc = f.scan.ptr[i].crc_so_far;
3609     foreach (immutable j; 0..m) crc = crc32_update(crc, data[nn+j]);
3610     f.scan.ptr[i].bytes_left -= m;
3611     f.scan.ptr[i].crc_so_far = crc;
3612     if (f.scan.ptr[i].bytes_left == 0) {
3613       // does it match?
3614       if (f.scan.ptr[i].crc_so_far == f.scan.ptr[i].goal_crc) {
3615         // Houston, we have page
3616         data_len = nn+m; // consumption amount is wherever that scan ended
3617         f.page_crc_tests = -1; // drop out of page scan mode
3618         f.previous_length = 0; // decode-but-don't-output one frame
3619         f.next_seg = -1;       // start a new page
3620         f.current_loc = f.scan.ptr[i].sample_loc; // set the current sample location to the amount we'd have decoded had we decoded this page
3621         f.current_loc_valid = f.current_loc != ~0U;
3622         return data_len;
3623       }
3624       // delete entry
3625       f.scan.ptr[i] = f.scan.ptr[--f.page_crc_tests];
3626     } else {
3627       ++i;
3628     }
3629   }
3630 
3631   return data_len;
3632 }
3633 +/
3634 
3635 uint vorbis_find_page (VorbisDecoder* f, uint* end, uint* last) {
3636   for (;;) {
3637     if (f.eof) return 0;
3638     auto n = get8(f);
3639     if (n == 0x4f) { // page header candidate
3640       uint retry_loc = f.fileOffset;
3641       // check if we're off the end of a file_section stream
3642       if (retry_loc-25 > f.stream_len) return 0;
3643       // check the rest of the header
3644       int i = void;
3645       for (i = 1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break;
3646       if (f.eof) return 0;
3647       if (i == 4) {
3648         ubyte[27] header;
3649         //for (i=0; i < 4; ++i) header[i] = ogg_page_header[i];
3650         header[0..4] = cast(immutable(ubyte)[])ogg_page_header[0..4];
3651         for (i = 4; i < 27; ++i) header[i] = get8(f);
3652         if (f.eof) return 0;
3653         if (header[4] != 0) goto invalid;
3654         uint goal = header[22]+(header[23]<<8)+(header[24]<<16)+(header[25]<<24);
3655         for (i = 22; i < 26; ++i) header[i] = 0;
3656         uint crc = 0;
3657         for (i = 0; i < 27; ++i) crc = crc32_update(crc, header[i]);
3658         uint len = 0;
3659         for (i = 0; i < header[26]; ++i) {
3660           auto s = get8(f);
3661           crc = crc32_update(crc, s);
3662           len += s;
3663         }
3664         if (len && f.eof) return 0;
3665         for (i = 0; i < len; ++i) crc = crc32_update(crc, get8(f));
3666         // finished parsing probable page
3667         if (crc == goal) {
3668           // we could now check that it's either got the last
3669           // page flag set, OR it's followed by the capture
3670           // pattern, but I guess TECHNICALLY you could have
3671           // a file with garbage between each ogg page and recover
3672           // from it automatically? So even though that paranoia
3673           // might decrease the chance of an invalid decode by
3674           // another 2^32, not worth it since it would hose those
3675           // invalid-but-useful files?
3676           if (end) *end = f.fileOffset;
3677           if (last) *last = (header[5]&0x04 ? 1 : 0);
3678           set_file_offset(f, retry_loc-1);
3679           return 1;
3680         }
3681       }
3682      invalid:
3683       // not a valid page, so rewind and look for next one
3684       set_file_offset(f, retry_loc);
3685     }
3686   }
3687   assert(0);
3688 }
3689 
3690 enum SAMPLE_unknown = 0xffffffff;
3691 
3692 // seeking is implemented with a binary search, which narrows down the range to
3693 // 64K, before using a linear search (because finding the synchronization
3694 // pattern can be expensive, and the chance we'd find the end page again is
3695 // relatively high for small ranges)
3696 //
3697 // two initial interpolation-style probes are used at the start of the search
3698 // to try to bound either side of the binary search sensibly, while still
3699 // working in O(log n) time if they fail.
3700 int get_seek_page_info (VorbisDecoder* f, ProbedPage* z) {
3701   ubyte[27] header;
3702   ubyte[255] lacing;
3703 
3704   // record where the page starts
3705   z.page_start = f.fileOffset;
3706   
3707   // This is put here to turn off IDE warnings
3708   uint discardConsumer;
3709 
3710   // parse the header
3711   discardConsumer = getn(f, header.ptr, 27);
3712   if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0;
3713   discardConsumer = getn(f, lacing.ptr, header[26]);
3714 
3715   // determine the length of the payload
3716   uint len = 0;
3717   foreach (immutable i; 0..header[26]) len += lacing[i];
3718 
3719   // this implies where the page ends
3720   z.page_end = z.page_start+27+header[26]+len;
3721 
3722   // read the last-decoded sample out of the data
3723   z.last_decoded_sample = header[6]+(header[7]<<8)+(header[8]<<16)+(header[9]<<24);
3724 
3725   // restore file state to where we were
3726   set_file_offset(f, z.page_start);
3727   return 1;
3728 }
3729 
3730 // rarely used function to seek back to the preceeding page while finding the start of a packet
3731 int go_to_page_before (VorbisDecoder* f, uint limit_offset) {
3732   uint previous_safe, end;
3733 
3734   // now we want to seek back 64K from the limit
3735   if (limit_offset >= 65_536 && limit_offset-65_536 >= f.first_audio_page_offset) {
3736     previous_safe = limit_offset-65_536;
3737   } else {
3738     previous_safe = f.first_audio_page_offset;
3739   }
3740 
3741   set_file_offset(f, previous_safe);
3742 
3743   while (vorbis_find_page(f, &end, null)) {
3744     if (end >= limit_offset && f.fileOffset < limit_offset) return 1;
3745     set_file_offset(f, end);
3746   }
3747 
3748   return 0;
3749 }
3750 
3751 // implements the search logic for finding a page and starting decoding. if
3752 // the function succeeds, current_loc_valid will be true and current_loc will
3753 // be less than or equal to the provided sample number (the closer the
3754 // better).
3755 int seek_to_sample_coarse (VorbisDecoder* f, uint sample_number) {
3756   ProbedPage left, right, mid;
3757   int i, start_seg_with_known_loc, end_pos, page_start;
3758   uint delta, stream_length, padding;
3759   double offset, bytes_per_sample;
3760   int probe = 0;
3761 
3762   // find the last page and validate the target sample
3763   stream_length = f.streamLengthInSamples;
3764   if (stream_length == 0) return error(f, STBVorbisError.seek_without_length);
3765   if (sample_number > stream_length) return error(f, STBVorbisError.seek_invalid);
3766 
3767   // this is the maximum difference between the window-center (which is the
3768   // actual granule position value), and the right-start (which the spec
3769   // indicates should be the granule position (give or take one)).
3770   padding = ((f.blocksize_1-f.blocksize_0)>>2);
3771   if (sample_number < padding) sample_number = 0; else sample_number -= padding;
3772 
3773   left = f.p_first;
3774   while (left.last_decoded_sample == ~0U) {
3775     // (untested) the first page does not have a 'last_decoded_sample'
3776     set_file_offset(f, left.page_end);
3777     if (!get_seek_page_info(f, &left)) goto error;
3778   }
3779 
3780   right = f.p_last;
3781   debug(stb_vorbis) assert(right.last_decoded_sample != ~0U);
3782 
3783   // starting from the start is handled differently
3784   if (sample_number <= left.last_decoded_sample) {
3785     f.seekStart;
3786     return 1;
3787   }
3788 
3789   while (left.page_end != right.page_start) {
3790     debug(stb_vorbis) assert(left.page_end < right.page_start);
3791     // search range in bytes
3792     delta = right.page_start-left.page_end;
3793     if (delta <= 65_536) {
3794       // there's only 64K left to search - handle it linearly
3795       set_file_offset(f, left.page_end);
3796     } else {
3797       if (probe < 2) {
3798         if (probe == 0) {
3799           // first probe (interpolate)
3800           double data_bytes = right.page_end-left.page_start;
3801           bytes_per_sample = data_bytes/right.last_decoded_sample;
3802           offset = left.page_start+bytes_per_sample*(sample_number-left.last_decoded_sample);
3803         } else {
3804           // second probe (try to bound the other side)
3805           double error = (cast(double)sample_number-mid.last_decoded_sample)*bytes_per_sample;
3806           if (error >= 0 && error <  8000) error =  8000;
3807           if (error <  0 && error > -8000) error = -8000;
3808           offset += error*2;
3809         }
3810 
3811         // ensure the offset is valid
3812         if (offset < left.page_end) offset = left.page_end;
3813         if (offset > right.page_start-65_536) offset = right.page_start-65_536;
3814 
3815         set_file_offset(f, cast(uint)offset);
3816       } else {
3817         // binary search for large ranges (offset by 32K to ensure
3818         // we don't hit the right page)
3819         set_file_offset(f, left.page_end+(delta/2)-32_768);
3820       }
3821 
3822       if (!vorbis_find_page(f, null, null)) goto error;
3823     }
3824 
3825     for (;;) {
3826       if (!get_seek_page_info(f, &mid)) goto error;
3827       if (mid.last_decoded_sample != ~0U) break;
3828       // (untested) no frames end on this page
3829       set_file_offset(f, mid.page_end);
3830       debug(stb_vorbis) assert(mid.page_start < right.page_start);
3831     }
3832 
3833     // if we've just found the last page again then we're in a tricky file,
3834     // and we're close enough.
3835     if (mid.page_start == right.page_start) break;
3836 
3837     if (sample_number < mid.last_decoded_sample) right = mid; else left = mid;
3838 
3839     ++probe;
3840   }
3841 
3842   // seek back to start of the last packet
3843   page_start = left.page_start;
3844   set_file_offset(f, page_start);
3845   if (!start_page(f)) return error(f, STBVorbisError.seek_failed);
3846   end_pos = f.end_seg_with_known_loc;
3847   debug(stb_vorbis) assert(end_pos >= 0);
3848 
3849   for (;;) {
3850     for (i = end_pos; i > 0; --i) if (f.segments.ptr[i-1] != 255) break;
3851     start_seg_with_known_loc = i;
3852     if (start_seg_with_known_loc > 0 || !(f.page_flag&PAGEFLAG_continued_packet)) break;
3853     // (untested) the final packet begins on an earlier page
3854     if (!go_to_page_before(f, page_start)) goto error;
3855     page_start = f.fileOffset;
3856     if (!start_page(f)) goto error;
3857     end_pos = f.segment_count-1;
3858   }
3859 
3860   // prepare to start decoding
3861   f.current_loc_valid = false;
3862   f.last_seg = false;
3863   f.valid_bits = 0;
3864   f.packet_bytes = 0;
3865   f.bytes_in_seg = 0;
3866   f.previous_length = 0;
3867   f.next_seg = start_seg_with_known_loc;
3868 
3869   for (i = 0; i < start_seg_with_known_loc; ++i) skip(f, f.segments.ptr[i]);
3870 
3871   // start decoding (optimizable - this frame is generally discarded)
3872   if (!vorbis_pump_first_frame(f)) return 0;
3873   if (f.current_loc > sample_number) return error(f, STBVorbisError.seek_failed);
3874   return 1;
3875 
3876 error:
3877   // try to restore the file to a valid state
3878   f.seekStart;
3879   return error(f, STBVorbisError.seek_failed);
3880 }
3881 
3882 // the same as vorbis_decode_initial, but without advancing
3883 int peek_decode_initial (
3884 VorbisDecoder* f,
3885 int* p_left_start,
3886 int* p_left_end,
3887 int* p_right_start,
3888 int* p_right_end,
3889 int* mode) {
3890   if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0;
3891 
3892   // either 1 or 2 bytes were read, figure out which so we can rewind
3893   int bits_read = 1+ilog(f.mode_count-1);
3894   if (f.mode_config.ptr[*mode].blockflag) bits_read += 2;
3895   int bytes_read = (bits_read+7)/8;
3896 
3897   f.bytes_in_seg += bytes_read;
3898   f.packet_bytes -= bytes_read;
3899   skip(f, -bytes_read);
3900   if (f.next_seg == -1) f.next_seg = f.segment_count-1; else --f.next_seg;
3901   f.valid_bits = 0;
3902 
3903   return 1;
3904 }
3905 
3906 // ////////////////////////////////////////////////////////////////////////// //
3907 // utility and supporting functions for getting s16 samples
3908 enum PLAYBACK_MONO  = (1<<0);
3909 enum PLAYBACK_LEFT  = (1<<1);
3910 enum PLAYBACK_RIGHT = (1<<2);
3911 
3912 enum L = (PLAYBACK_LEFT |PLAYBACK_MONO);
3913 enum C = (PLAYBACK_LEFT |PLAYBACK_RIGHT|PLAYBACK_MONO);
3914 enum R = (PLAYBACK_RIGHT|PLAYBACK_MONO);
3915 
3916 immutable byte[6][7] channel_position = [
3917   [ 0 ],
3918   [ C ],
3919   [ L, R ],
3920   [ L, C, R ],
3921   [ L, R, L, R ],
3922   [ L, C, R, L, R ],
3923   [ L, C, R, L, R, C ],
3924 ];
3925 
3926 
3927 version(STB_VORBIS_NO_FAST_SCALED_FLOAT) {
3928   enum declfcvar(string name) = "{}";
3929   template FAST_SCALED_FLOAT_TO_INT(string x, string s) {
3930     static assert(s == "15");
3931     enum FAST_SCALED_FLOAT_TO_INT = q{
3932         import core.stdc.math : lrintf;
3933         int v = lrintf((${x})*32768.0f);
3934         }.cmacroFixVars!"x"(x);
3935   }
3936 } else {
3937   //k8: actually, this is only marginally faster than using `lrintf()`, but anyway...
3938   align(1) union float_conv {
3939   align(1):
3940     float f;
3941     int i;
3942   }
3943   enum declfcvar(string name) = "float_conv "~name~" = void;";
3944   static assert(float_conv.i.sizeof == 4 && float_conv.f.sizeof == 4);
3945   // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
3946   //#define check_endianness()
3947   enum MAGIC(string SHIFT) = q{(1.5f*(1<<(23-${SHIFT}))+0.5f/(1<<${SHIFT}))}.cmacroFixVars!("SHIFT")(SHIFT);
3948   enum ADDEND(string SHIFT) = q{(((150-${SHIFT})<<23)+(1<<22))}.cmacroFixVars!("SHIFT")(SHIFT);
3949   enum FAST_SCALED_FLOAT_TO_INT(string x, string s) = q{temp.f = (${x})+${MAGIC}; int v = temp.i-${ADDEND};}
3950     .cmacroFixVars!("x", "s", "MAGIC", "ADDEND")(x, s, MAGIC!(s), ADDEND!(s));
3951 }
3952 
3953 void copy_samples (short* dest, float* src, int len) {
3954   //check_endianness();
3955   mixin(declfcvar!"temp");
3956   foreach (immutable _; 0..len) {
3957     mixin(FAST_SCALED_FLOAT_TO_INT!("*src", "15"));
3958     if (cast(uint)(v+32_768) > 65_535) v = (v < 0 ? -32_768 : 32_767);
3959     *dest++ = cast(short)v; //k8
3960     ++src;
3961   }
3962 }
3963 
3964 void compute_samples (int mask, short* output, int num_c, float** data, int d_offset, int len) {
3965   import core.stdc.string : memset;
3966   enum BUFFER_SIZE = 32;
3967   float[BUFFER_SIZE] buffer;
3968   int n = BUFFER_SIZE;
3969   //check_endianness();
3970   mixin(declfcvar!"temp");
3971   for (uint o = 0; o < len; o += BUFFER_SIZE) {
3972     memset(buffer.ptr, 0, (buffer).sizeof);
3973     if (o+n > len) n = len-o;
3974     foreach (immutable j; 0..num_c) {
3975       if (channel_position[num_c].ptr[j]&mask) foreach (immutable i; 0..n) buffer.ptr[i] += data[j][d_offset+o+i];
3976     }
3977     foreach (immutable i; 0..n) {
3978       mixin(FAST_SCALED_FLOAT_TO_INT!("buffer[i]", "15"));
3979       if (cast(uint)(v+32_768) > 65_535) v = (v < 0 ? -32_768 : 32_767);
3980       output[o+i] = cast(short)v; //k8
3981     }
3982   }
3983 }
3984 
3985 void compute_stereo_samples (short* output, int num_c, float** data, int d_offset, int len) {
3986   import core.stdc.string : memset;
3987 
3988   enum BUFFER_SIZE = 32;
3989   float[BUFFER_SIZE] buffer;
3990   int n = BUFFER_SIZE>>1;
3991   // o is the offset in the source data
3992   //check_endianness();
3993   mixin(declfcvar!"temp");
3994   for (uint o = 0; o < len; o += BUFFER_SIZE>>1) {
3995     // o2 is the offset in the output data
3996     int o2 = o<<1;
3997     memset(buffer.ptr, 0, buffer.sizeof);
3998     if (o+n > len) n = len-o;
3999     foreach (immutable j; 0..num_c) {
4000       int m = channel_position[num_c].ptr[j]&(PLAYBACK_LEFT|PLAYBACK_RIGHT);
4001       if (m == (PLAYBACK_LEFT|PLAYBACK_RIGHT)) {
4002         foreach (immutable i; 0..n) {
4003           buffer.ptr[i*2+0] += data[j][d_offset+o+i];
4004           buffer.ptr[i*2+1] += data[j][d_offset+o+i];
4005         }
4006       } else if (m == PLAYBACK_LEFT) {
4007         foreach (immutable i; 0..n) buffer.ptr[i*2+0] += data[j][d_offset+o+i];
4008       } else if (m == PLAYBACK_RIGHT) {
4009         foreach (immutable i; 0..n) buffer.ptr[i*2+1] += data[j][d_offset+o+i];
4010       }
4011     }
4012     foreach (immutable i; 0..n<<1) {
4013       mixin(FAST_SCALED_FLOAT_TO_INT!("buffer[i]", "15"));
4014       if (cast(uint)(v+32_768) > 65_535) v = (v < 0 ? -32_768 : 32_767);
4015       output[o2+i] = cast(short)v; //k8
4016     }
4017   }
4018 }
4019 
4020 void convert_samples_short (
4021 int buf_c,
4022 short** buffer,
4023 int b_offset,
4024 int data_c,
4025 float** data,
4026 int d_offset,
4027 int samples) {
4028   
4029   import core.stdc.string : memset;
4030 
4031   if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
4032     immutable int[2][3] channel_selector = [ [0,0], [PLAYBACK_MONO,0], [PLAYBACK_LEFT, PLAYBACK_RIGHT] ];
4033     foreach (immutable i; 0..buf_c)
4034         compute_samples(channel_selector[buf_c].ptr[i], buffer[i]+b_offset, data_c, data, d_offset, samples);
4035   } else {
4036     int limit = (buf_c < data_c ? buf_c : data_c);
4037     foreach (immutable i; 0..limit) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
4038     foreach (immutable i; limit..buf_c) memset(buffer[i]+b_offset, 0, short.sizeof*samples);
4039   }
4040 }
4041 
4042 void convert_channels_short_interleaved (int buf_c, short* buffer, int data_c, float** data, int d_offset, int len) {
4043   //check_endianness();
4044   mixin(declfcvar!"temp");
4045   if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
4046     debug(stb_vorbis) assert(buf_c == 2);
4047     foreach (immutable i; 0..buf_c) compute_stereo_samples(buffer, data_c, data, d_offset, len);
4048   } else {
4049     int limit = (buf_c < data_c ? buf_c : data_c);
4050     foreach (immutable j; 0..len) {
4051       foreach (immutable i; 0..limit) {
4052         float f = data[i][d_offset+j];
4053         mixin(FAST_SCALED_FLOAT_TO_INT!("f", "15"));//data[i][d_offset+j], 15);
4054         if (cast(uint)(v+32_768) > 65_535) v = (v < 0 ? -32_768 : 32_767);
4055         *buffer++ = cast(short)v; //k8
4056       }
4057       foreach (immutable i; limit..buf_c) *buffer++ = 0;
4058     }
4059   }
4060 }
4061 } // @nogc
4062 
4063 
4064 public struct VorbisDecoder {
4065   // return # of bytes read, 0 on eof, -1 on error
4066   // if called with `buf is null`, do `close()`
4067   alias readCB = int delegate (void[] buf, uint ofs, VorbisDecoder* vb) nothrow @nogc;
4068 
4069   //TODO
4070   static struct Allocator {
4071   static nothrow @nogc: // because
4072     void* alloc (uint sz, VorbisDecoder* vb) {
4073       import core.stdc.stdlib : malloc;
4074       return malloc(sz);
4075     }
4076     void free (void* p, VorbisDecoder* vb) {
4077       import core.stdc.stdlib : free;
4078       free(p);
4079     }
4080     void* allocTemp (uint sz, VorbisDecoder* vb) {
4081       import core.stdc.stdlib : malloc;
4082       return malloc(sz);
4083     }
4084     void freeTemp (void* p, uint sz, VorbisDecoder* vb) {
4085       import core.stdc.stdlib : free;
4086       free(p);
4087     }
4088     uint tempSave (VorbisDecoder* vb) { return 0; }
4089     void tempRestore (uint pos, VorbisDecoder* vb) {}
4090   }
4091 
4092 nothrow @nogc:
4093 private:
4094   bool isOpened;
4095   readCB stmread;
4096   uint stlastofs = uint.max;
4097   uint stst;
4098   uint stpos;
4099   uint stend;
4100   bool stclose;
4101   FILE* stfl;
4102 
4103   //ubyte* stream;
4104   //ubyte* stream_start;
4105   //ubyte* stream_end;
4106   //uint stream_len;
4107 
4108   /+bool push_mode;+/
4109 
4110   uint first_audio_page_offset;
4111 
4112   ProbedPage p_first, p_last;
4113 
4114   // memory management
4115   Allocator alloc;
4116   int setup_offset;
4117   int temp_offset;
4118 
4119   // run-time results
4120   bool eof = true;
4121   STBVorbisError error;
4122 
4123   // header info
4124   int[2] blocksize;
4125   int blocksize_0, blocksize_1;
4126   int codebook_count;
4127   Codebook* codebooks;
4128   int floor_count;
4129   ushort[64] floor_types; // varies
4130   Floor* floor_config;
4131   int residue_count;
4132   ushort[64] residue_types; // varies
4133   Residue* residue_config;
4134   int mapping_count;
4135   Mapping* mapping;
4136   int mode_count;
4137   Mode[64] mode_config;  // varies
4138 
4139   uint total_samples;
4140 
4141   // decode buffer
4142   float*[STB_VORBIS_MAX_CHANNELS] channel_buffers;
4143   float*[STB_VORBIS_MAX_CHANNELS] outputs;
4144 
4145   float*[STB_VORBIS_MAX_CHANNELS] previous_window;
4146   int previous_length;
4147 
4148   version(STB_VORBIS_NO_DEFER_FLOOR) {
4149     float*[STB_VORBIS_MAX_CHANNELS] floor_buffers;
4150   } else {
4151     short*[STB_VORBIS_MAX_CHANNELS] finalY;
4152   }
4153 
4154   uint current_loc; // sample location of next frame to decode
4155   int current_loc_valid;
4156 
4157   // per-blocksize precomputed data
4158 
4159   // twiddle factors
4160   float*[2] A, B, C;
4161   float*[2] window;
4162   ushort*[2] bit_reverse;
4163 
4164   // current page/packet/segment streaming info
4165   uint serial; // stream serial number for verification
4166   int last_page;
4167   int segment_count;
4168   ubyte[255] segments;
4169   ubyte page_flag;
4170   ubyte bytes_in_seg;
4171   ubyte first_decode;
4172   int next_seg;
4173   int last_seg;  // flag that we're on the last segment
4174   int last_seg_which; // what was the segment number of the last seg?
4175   uint acc;
4176   int valid_bits;
4177   int packet_bytes;
4178   int end_seg_with_known_loc;
4179   uint known_loc_for_packet;
4180   int discard_samples_deferred;
4181   uint samples_output;
4182 
4183   // push mode scanning
4184   /+
4185   int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
4186   CRCscan[STB_VORBIS_PUSHDATA_CRC_COUNT] scan;
4187   +/
4188 
4189   // sample-access
4190   int channel_buffer_start;
4191   int channel_buffer_end;
4192 
4193   // k8: 'cause i'm evil
4194   // user-accessible info
4195   uint sample_rate;
4196   int vrchannels;
4197 
4198   uint setup_memory_required;
4199   uint temp_memory_required;
4200   uint setup_temp_memory_required;
4201 
4202   bool read_comments;
4203   ubyte* comment_data;
4204   uint comment_size;
4205 
4206   // functions to get comment data
4207   uint comment_data_pos;
4208 
4209 public:
4210   int rawRead (void[] buf) {
4211     static if (__VERSION__ > 2067) pragma(inline, true);
4212     if (isOpened && buf.length > 0 && stpos < stend) {
4213       if (stend-stpos < buf.length) buf = buf[0..stend-stpos];
4214       auto rd = stmread(buf, stpos, &this);
4215       if (rd > 0) stpos += rd;
4216       return rd;
4217     }
4218     return 0;
4219   }
4220   void rawSkip (int n) {
4221     static if (__VERSION__ > 2067) pragma(inline, true);
4222     if (isOpened && n > 0) {
4223         if ((stpos += n) > stend) stpos = stend;
4224         }
4225     }
4226   void rawSeek (int n) {
4227     static if (__VERSION__ > 2067) pragma(inline, true);
4228     if (isOpened) {
4229         stpos = stst+(n < 0 ? 0 : n); if (stpos > stend) stpos = stend;
4230         }
4231     }
4232   void rawClose () {
4233     static if (__VERSION__ > 2067) pragma(inline, true);
4234     if (isOpened) {
4235         isOpened = false; stmread(null, 0, &this);
4236         }
4237     }
4238 
4239 final:
4240   void doInit () {
4241     import core.stdc.string : memset;
4242     /*
4243     if (z) {
4244       alloc = *z;
4245       alloc.alloc_buffer_length_in_bytes = (alloc.alloc_buffer_length_in_bytes+3)&~3;
4246       temp_offset = alloc.alloc_buffer_length_in_bytes;
4247     }
4248     */
4249     eof = false;
4250     error = STBVorbisError.no_error;
4251     /+stream = null;+/
4252     codebooks = null;
4253     /+page_crc_tests = -1;+/
4254   }
4255 
4256   static int stflRead (void[] buf, uint ofs, VorbisDecoder* vb) {
4257     if (buf !is null) {
4258       //{ import core.stdc.stdio; printf("stflRead: ofs=%u; len=%u\n", ofs, cast(uint)buf.length); }
4259       if (vb.stlastofs != ofs) {
4260         import core.stdc.stdio : fseek, SEEK_SET;
4261         vb.stlastofs = ofs;
4262         fseek(vb.stfl, ofs, SEEK_SET);
4263       }
4264       import core.stdc.stdio : fread;
4265       return cast(int)fread(buf.ptr, 1, buf.length, vb.stfl);
4266     } else {
4267       if (vb.stclose) {
4268         import core.stdc.stdio : fclose;
4269         if (vb.stfl !is null) fclose(vb.stfl);
4270       }
4271       vb.stfl = null;
4272       return 0;
4273     }
4274   }
4275 
4276 public:
4277   ~this () {
4278     close();
4279    }
4280 
4281   this (int asize, readCB rcb) {
4282   	assert(rcb !is null);
4283 	stend = (asize > 0 ? asize : 0);
4284 	stmread = rcb;
4285 	isOpened = true;
4286 	eof = false;
4287 	read_comments = true;
4288 	if (start_decoder(&this)) {
4289         // This is put here to turn off IDE warnings
4290         uint discardConsumer;
4291 		discardConsumer = vorbis_pump_first_frame(&this);
4292 		return;
4293 	}
4294   }
4295   this (FILE* fl, bool doclose=true) {
4296     open(fl, doclose);
4297   }
4298   this (const(char)[] filename) {
4299     open(filename);
4300   }
4301 
4302   @property bool closed () {
4303     return !isOpened;
4304   }
4305 
4306   @property bool opened () {
4307     return isOpened;
4308   }
4309 
4310   void open (FILE *fl, bool doclose=true) {
4311     import core.stdc.stdio : ftell, fseek, SEEK_SET, SEEK_END;
4312     close();
4313     if (fl is null) { error = STBVorbisError.invalid_stream; return; }
4314     stclose = doclose;
4315     stst = stpos = cast(uint)ftell(fl);
4316     fseek(fl, 0, SEEK_END);
4317     stend = cast(uint)ftell(fl);
4318     stlastofs = stlastofs.max;
4319     stclose = false;
4320     stfl = fl;
4321     import std.functional : toDelegate;
4322     stmread = toDelegate(&stflRead);
4323     isOpened = true;
4324     eof = false;
4325     read_comments = true;
4326     if (start_decoder(&this)) {
4327       // This is put here to turn off IDE warnings
4328       uint discardConsumer;
4329       discardConsumer = vorbis_pump_first_frame(&this);
4330       return;
4331     }
4332     auto err = error;
4333     close();    
4334     error = err;
4335   }
4336 
4337   void open (const(char)[] filename) {
4338     import core.stdc.stdio : fopen;
4339     import std.internal.cstring; // sorry
4340     close();
4341     FILE* fl = fopen(filename.tempCString, "rb");
4342     if (fl is null) {
4343         error = STBVorbisError.file_open_failure; return;
4344     }
4345     open(fl, true);
4346   }
4347 
4348   /+
4349   void openPushdata(void* data, int data_len, // the memory available for decoding
4350                     int* data_used)           // only defined on success
4351   {
4352     close();
4353     eof = false;
4354     stream = cast(ubyte*)data;
4355     stream_end = stream+data_len;
4356     push_mode = true;
4357     if (!start_decoder(this)) {
4358       auto err = error;
4359       if (eof) err = STBVorbisError.need_more_data; else close();
4360       error = err;
4361       return;
4362     }
4363     *data_used = stream-(cast(ubyte*)data);
4364     error = STBVorbisError.no_error;
4365   }
4366   +/
4367 
4368   void close () {
4369     import core.stdc.string : memset;
4370 
4371     setup_free(&this, this.comment_data);
4372     if (this.residue_config) {
4373       foreach (immutable i; 0..this.residue_count) {
4374         Residue* r = this.residue_config+i;
4375         if (r.classdata) {
4376           foreach (immutable j; 0..this.codebooks[r.classbook].entries) setup_free(&this, r.classdata[j]);
4377           setup_free(&this, r.classdata);
4378         }
4379         setup_free(&this, r.residue_books);
4380       }
4381     }
4382 
4383     if (this.codebooks) {
4384       foreach (immutable i; 0..this.codebook_count) {
4385         Codebook* c = this.codebooks+i;
4386         setup_free(&this, c.codeword_lengths);
4387         setup_free(&this, c.multiplicands);
4388         setup_free(&this, c.codewords);
4389         setup_free(&this, c.sorted_codewords);
4390         // c.sorted_values[-1] is the first entry in the array
4391         setup_free(&this, c.sorted_values ? c.sorted_values-1 : null);
4392       }
4393       setup_free(&this, this.codebooks);
4394     }
4395     setup_free(&this, this.floor_config);
4396     setup_free(&this, this.residue_config);
4397     if (this.mapping) {
4398       foreach (immutable i; 0..this.mapping_count) setup_free(&this, this.mapping[i].chan);
4399       setup_free(&this, this.mapping);
4400     }
4401     foreach (immutable i; 0..(this.vrchannels > STB_VORBIS_MAX_CHANNELS ? STB_VORBIS_MAX_CHANNELS : this.vrchannels)) {
4402       setup_free(&this, this.channel_buffers.ptr[i]);
4403       setup_free(&this, this.previous_window.ptr[i]);
4404       version(STB_VORBIS_NO_DEFER_FLOOR) setup_free(this, this.floor_buffers.ptr[i]);
4405       setup_free(&this, this.finalY.ptr[i]);
4406     }
4407     foreach (immutable i; 0..2) {
4408       setup_free(&this, this.A.ptr[i]);
4409       setup_free(&this, this.B.ptr[i]);
4410       setup_free(&this, this.C.ptr[i]);
4411       setup_free(&this, this.window.ptr[i]);
4412       setup_free(&this, this.bit_reverse.ptr[i]);
4413     }
4414 
4415     rawClose();
4416     isOpened = false;
4417     stmread = null;
4418     stlastofs = uint.max;
4419     stst = 0;
4420     stpos = 0;
4421     stend = 0;
4422     stclose = false;
4423     stfl = null;
4424 
4425     sample_rate = 0;
4426     vrchannels = 0;
4427 
4428     setup_memory_required = 0;
4429     temp_memory_required = 0;
4430     setup_temp_memory_required = 0;
4431 
4432     read_comments = 0;
4433     comment_data = null;
4434     comment_size = 0;
4435 
4436     comment_data_pos = 0;
4437 
4438     /+
4439     stream = null;
4440     stream_start = null;
4441     stream_end = null;
4442     +/
4443 
4444     //stream_len = 0;
4445 
4446     /+push_mode = false;+/
4447 
4448     first_audio_page_offset = 0;
4449 
4450     p_first = p_first.init;
4451     p_last = p_last.init;
4452 
4453     setup_offset = 0;
4454     temp_offset = 0;
4455 
4456     eof = true;
4457     error = STBVorbisError.no_error;
4458 
4459     blocksize[] = 0;
4460     blocksize_0 = 0;
4461     blocksize_1 = 0;
4462     codebook_count = 0;
4463     codebooks = null;
4464     floor_count = 0;
4465     floor_types[] = 0;
4466     floor_config = null;
4467     residue_count = 0;
4468     residue_types[] = 0;
4469     residue_config = null;
4470     mapping_count = 0;
4471     mapping = null;
4472     mode_count = 0;
4473     mode_config[] = Mode.init;
4474 
4475     total_samples = 0;
4476 
4477     channel_buffers[] = null;
4478     outputs[] = null;
4479 
4480     previous_window[] = null;
4481     previous_length = 0;
4482 
4483     version(STB_VORBIS_NO_DEFER_FLOOR) {
4484       floor_buffers[] = null;
4485     } else {
4486       finalY[] = null;
4487     }
4488 
4489     current_loc = 0;
4490     current_loc_valid = 0;
4491 
4492     A[] = null;
4493     B[] = null;
4494     C[] = null;
4495     window[] = null;
4496     bit_reverse = null;
4497 
4498     serial = 0;
4499     last_page = 0;
4500     segment_count = 0;
4501     segments[] = 0;
4502     page_flag = 0;
4503     bytes_in_seg = 0;
4504     first_decode = 0;
4505     next_seg = 0;
4506     last_seg = 0;
4507     last_seg_which = 0;
4508     acc = 0;
4509     valid_bits = 0;
4510     packet_bytes = 0;
4511     end_seg_with_known_loc = 0;
4512     known_loc_for_packet = 0;
4513     discard_samples_deferred = 0;
4514     samples_output = 0;
4515 
4516     /+
4517     page_crc_tests = -1;
4518     scan[] = CRCscan.init;
4519     +/
4520 
4521     channel_buffer_start = 0;
4522     channel_buffer_end = 0;
4523   }
4524 
4525   @property const pure {
4526     int getSampleOffset () { return (current_loc_valid ? current_loc : -1); }
4527 
4528     @property ubyte chans () { return (isOpened ? cast(ubyte)this.vrchannels : 0); }
4529     @property uint sampleRate () { return (isOpened ? this.sample_rate : 0); }
4530     @property uint maxFrameSize () { return (isOpened ? this.blocksize_1>>1 : 0); }
4531 
4532     @property uint getSetupMemoryRequired () { return (isOpened ? this.setup_memory_required : 0); }
4533     @property uint getSetupTempMemoryRequired () { return (isOpened ? this.setup_temp_memory_required : 0); }
4534     @property uint getTempMemoryRequired () { return (isOpened ? this.temp_memory_required : 0); }
4535   }
4536 
4537   // will clear last error
4538   @property int lastError () {
4539     int e = error;
4540     error = STBVorbisError.no_error;
4541     return e;
4542   }
4543 
4544   // PUSHDATA API
4545   /+
4546   void flushPushdata () {
4547     if (push_mode) {
4548       previous_length = 0;
4549       page_crc_tests = 0;
4550       discard_samples_deferred = 0;
4551       current_loc_valid = false;
4552       first_decode = false;
4553       samples_output = 0;
4554       channel_buffer_start = 0;
4555       channel_buffer_end = 0;
4556     }
4557   }
4558 
4559   // return value: number of bytes we used
4560   int decodeFramePushdata(
4561            void* data, int data_len, // the memory available for decoding
4562            int* channels,            // place to write number of float* buffers
4563            float*** output,          // place to write float** array of float* buffers
4564            int* samples              // place to write number of output samples
4565        )
4566   {
4567     if (!this.push_mode) return .error(this, STBVorbisError.invalid_api_mixing);
4568 
4569     if (this.page_crc_tests >= 0) {
4570       *samples = 0;
4571       return vorbis_search_for_page_pushdata(this, cast(ubyte*)data, data_len);
4572     }
4573 
4574     this.stream = cast(ubyte*)data;
4575     this.stream_end = this.stream+data_len;
4576     this.error = STBVorbisError.no_error;
4577 
4578     // check that we have the entire packet in memory
4579     if (!is_whole_packet_present(this, false)) {
4580       *samples = 0;
4581       return 0;
4582     }
4583 
4584     int len, left, right;
4585 
4586     if (!vorbis_decode_packet(this, &len, &left, &right)) {
4587       // save the actual error we encountered
4588       STBVorbisError error = this.error;
4589       if (error == STBVorbisError.bad_packet_type) {
4590         // flush and resynch
4591         this.error = STBVorbisError.no_error;
4592         while (get8_packet(this) != EOP) if (this.eof) break;
4593         *samples = 0;
4594         return this.stream-data;
4595       }
4596       if (error == STBVorbisError.continued_packet_flag_invalid) {
4597         if (this.previous_length == 0) {
4598           // we may be resynching, in which case it's ok to hit one
4599           // of these; just discard the packet
4600           this.error = STBVorbisError.no_error;
4601           while (get8_packet(this) != EOP) if (this.eof) break;
4602           *samples = 0;
4603           return this.stream-data;
4604         }
4605       }
4606       // if we get an error while parsing, what to do?
4607       // well, it DEFINITELY won't work to continue from where we are!
4608       flushPushdata();
4609       // restore the error that actually made us bail
4610       this.error = error;
4611       *samples = 0;
4612       return 1;
4613     }
4614 
4615     // success!
4616     len = vorbis_finish_frame(this, len, left, right);
4617     foreach (immutable i; 0..this.vrchannels) this.outputs.ptr[i] = this.channel_buffers.ptr[i]+left;
4618 
4619     if (channels) *channels = this.vrchannels;
4620     *samples = len;
4621     *output = this.outputs.ptr;
4622     return this.stream-data;
4623   }
4624   +/
4625 
4626   uint fileOffset () {
4627     if (/+push_mode ||+/ !isOpened) return 0;
4628     /+if (stream !is null) return cast(uint)(stream-stream_start);+/
4629     return (stpos > stst ? stpos-stst : 0);
4630   }
4631 
4632   uint stream_len () { return stend-stst; }
4633 
4634   // DATA-PULLING API
4635   int seekFrame (uint sample_number) {
4636     uint max_frame_samples;
4637 
4638     /+if (this.push_mode) return -.error(this, STBVorbisError.invalid_api_mixing);+/
4639 
4640     // fast page-level search
4641     if (!seek_to_sample_coarse(&this, sample_number)) return 0;
4642 
4643     assert(this.current_loc_valid);
4644     assert(this.current_loc <= sample_number);
4645 
4646     // linear search for the relevant packet
4647     max_frame_samples = (this.blocksize_1*3-this.blocksize_0)>>2;
4648     while (this.current_loc < sample_number) {
4649       int left_start, left_end, right_start, right_end, mode, frame_samples;
4650       if (!peek_decode_initial(&this, &left_start, &left_end, &right_start, &right_end, &mode))
4651         return .error(&this, STBVorbisError.seek_failed);
4652       // calculate the number of samples returned by the next frame
4653       frame_samples = right_start-left_start;
4654       if (this.current_loc+frame_samples > sample_number) {
4655         return 1; // the next frame will contain the sample
4656       } else if (this.current_loc+frame_samples+max_frame_samples > sample_number) {
4657         // there's a chance the frame after this could contain the sample
4658         // This is put here to turn off IDE warnings
4659         uint discardConsumer;
4660         discardConsumer = vorbis_pump_first_frame(&this);
4661       } else {
4662         // this frame is too early to be relevant
4663         this.current_loc += frame_samples;
4664         this.previous_length = 0;
4665         // This is put here to turn off IDE warnings
4666         uint discardConsumer;
4667         discardConsumer = maybe_start_packet(&this);
4668         flush_packet(&this);
4669       }
4670     }
4671     // the next frame will start with the sample
4672     assert(this.current_loc == sample_number);
4673     return 1;
4674   }
4675 
4676   int seek (uint sample_number) {
4677     if (!seekFrame(sample_number)) return 0;
4678     if (sample_number != this.current_loc) {
4679       int n;
4680       uint frame_start = this.current_loc;
4681       getFrameFloat(&n, null);
4682       assert(sample_number > frame_start);
4683       assert(this.channel_buffer_start+cast(int)(sample_number-frame_start) <= this.channel_buffer_end);
4684       this.channel_buffer_start += (sample_number-frame_start);
4685     }
4686     return 1;
4687   }
4688 
4689   bool seekStart () {
4690     /+if (push_mode) { .error(this, STBVorbisError.invalid_api_mixing); return; }+/
4691     set_file_offset(&this, first_audio_page_offset);
4692     previous_length = 0;
4693     first_decode = true;
4694     next_seg = -1;
4695     return vorbis_pump_first_frame(&this);
4696   }
4697 
4698   uint streamLengthInSamples () {
4699     uint restore_offset, previous_safe;
4700     uint end, last_page_loc;
4701 
4702     /+if (this.push_mode) return .error(this, STBVorbisError.invalid_api_mixing);+/
4703     if (!this.total_samples) {
4704       uint last;
4705       uint lo, hi;
4706       char[6] header;
4707 
4708       // first, store the current decode position so we can restore it
4709       restore_offset = fileOffset;
4710 
4711       // now we want to seek back 64K from the end (the last page must
4712       // be at most a little less than 64K, but let's allow a little slop)
4713       if (this.stream_len >= 65_536 && this.stream_len-65_536 >= this.first_audio_page_offset) {
4714         previous_safe = this.stream_len-65_536;
4715       } else {
4716         previous_safe = this.first_audio_page_offset;
4717       }
4718 
4719       set_file_offset(&this, previous_safe);
4720       // previous_safe is now our candidate 'earliest known place that seeking
4721       // to will lead to the final page'
4722 
4723       if (!vorbis_find_page(&this, &end, &last)) {
4724         // if we can't find a page, we're hosed!
4725         this.error = STBVorbisError.cant_find_last_page;
4726         this.total_samples = 0xffffffff;
4727         goto done;
4728       }
4729 
4730       // check if there are more pages
4731       last_page_loc = fileOffset;
4732 
4733       // stop when the last_page flag is set, not when we reach eof;
4734       // this allows us to stop short of a 'file_section' end without
4735       // explicitly checking the length of the section
4736       while (!last) {
4737         set_file_offset(&this, end);
4738         if (!vorbis_find_page(&this, &end, &last)) {
4739           // the last page we found didn't have the 'last page' flag set. whoops!
4740           break;
4741         }
4742         previous_safe = last_page_loc+1;
4743         last_page_loc = fileOffset;
4744       }
4745 
4746       set_file_offset(&this, last_page_loc);
4747 
4748       // parse the header
4749       // Needs to scope, otherwise dmd gives an error about goto
4750       {
4751         // This is put here to turn off IDE warnings
4752         uint discardConsumer;
4753         discardConsumer = getn(&this, cast(ubyte*)header, 6);
4754       }
4755       // extract the absolute granule position
4756       lo = get32(&this);
4757       hi = get32(&this);
4758       if (lo == 0xffffffff && hi == 0xffffffff) {
4759         this.error = STBVorbisError.cant_find_last_page;
4760         this.total_samples = SAMPLE_unknown;
4761         goto done;
4762       }
4763       if (hi) lo = 0xfffffffe; // saturate
4764       this.total_samples = lo;
4765 
4766       this.p_last.page_start = last_page_loc;
4767       this.p_last.page_end = end;
4768       this.p_last.last_decoded_sample = lo;
4769 
4770      done:
4771       set_file_offset(&this, restore_offset);
4772     }
4773     return (this.total_samples == SAMPLE_unknown ? 0 : this.total_samples);
4774   }
4775 
4776   float streamLengthInSeconds () {
4777     return (isOpened ? streamLengthInSamples()/cast(float)sample_rate : 0.0f);
4778   }
4779 
4780   int getFrameFloat (int* channels, float*** output) {
4781     int len, right, left;
4782     /+if (push_mode) return .error(this, STBVorbisError.invalid_api_mixing);+/
4783 
4784     if (!vorbis_decode_packet(&this, &len, &left, &right)) {
4785       channel_buffer_start = channel_buffer_end = 0;
4786       return 0;
4787     }
4788 
4789     len = vorbis_finish_frame(&this, len, left, right);
4790     foreach (immutable i; 0..this.vrchannels) this.outputs.ptr[i] = this.channel_buffers.ptr[i]+left;
4791 
4792     channel_buffer_start = left;
4793     channel_buffer_end = left+len;
4794 
4795     if (channels) *channels = this.vrchannels;
4796     if (output) *output = this.outputs.ptr;
4797     return len;
4798   }
4799 
4800   /+
4801   public VorbisDecoder* stb_vorbis_open_memory (const(void)* data, int len, int* error=null, STBVorbisAlloc* alloc=null) {
4802     VorbisDecoder* this;
4803     stb_vorbis_ctx p = void;
4804     if (data is null) return null;
4805     vorbis_init(&p, alloc);
4806     p.stream = cast(ubyte*)data;
4807     p.stream_end = cast(ubyte*)data+len;
4808     p.stream_start = cast(ubyte*)p.stream;
4809     p.stream_len = len;
4810     p.push_mode = false;
4811     if (start_decoder(&p)) {
4812       this = vorbis_alloc(&p);
4813       if (this) {
4814         *this = p;
4815         vorbis_pump_first_frame(this);
4816         return this;
4817       }
4818     }
4819     if (error) *error = p.error;
4820     vorbis_deinit(&p);
4821     return null;
4822   }
4823   +/
4824 
4825   // s16 samples API
4826   int getFrameShort (int num_c, short** buffer, int num_samples) {
4827     float** output;
4828     int len = getFrameFloat(null, &output);
4829     if (len > num_samples) len = num_samples;
4830     if (len) convert_samples_short(num_c, buffer, 0, vrchannels, output, 0, len);
4831     return len;
4832   }
4833 
4834   int getFrameShortInterleaved (int num_c, short* buffer, int num_shorts) {
4835     float** output;
4836     int len;
4837     if (num_c == 1) return getFrameShort(num_c, &buffer, num_shorts);
4838     len = getFrameFloat(null, &output);
4839     if (len) {
4840       if (len*num_c > num_shorts) len = num_shorts/num_c;
4841       convert_channels_short_interleaved(num_c, buffer, vrchannels, output, 0, len);
4842     }
4843     return len;
4844   }
4845 
4846   int getSamplesShortInterleaved (int channels, short* buffer, int num_shorts) {
4847     // Renamed this from outputs to scopeOutputs to stop override of outer scope's variable
4848     float** scopeOutputs;
4849     int len = num_shorts/channels;
4850     int n = 0;
4851     int z = this.vrchannels;
4852     if (z > channels) z = channels;
4853     while (n < len) {
4854       int k = channel_buffer_end-channel_buffer_start;
4855       if (n+k >= len) k = len-n;
4856       if (k)
4857         convert_channels_short_interleaved(channels, buffer, vrchannels, channel_buffers.ptr, channel_buffer_start, k);
4858       buffer += k*channels;
4859       n += k;
4860       channel_buffer_start += k;
4861       if (n == len) break;
4862       if (!getFrameFloat(null, &scopeOutputs)) break;
4863     }
4864     return n;
4865   }
4866 
4867   int getSamplesShort (int channels, short** buffer, int len) {
4868     // Renamed this from outputs to scopeOutputs to stop override of outer scope's variable
4869     float** scopeOutputs;
4870     int n = 0;
4871     int z = this.vrchannels;
4872     if (z > channels) z = channels;
4873     while (n < len) {
4874       int k = channel_buffer_end-channel_buffer_start;
4875       if (n+k >= len) k = len-n;
4876       if (k) convert_samples_short(channels, buffer, n, vrchannels, channel_buffers.ptr, channel_buffer_start, k);
4877       n += k;
4878       channel_buffer_start += k;
4879       if (n == len) break;
4880       if (!getFrameFloat(null, &scopeOutputs)) break;
4881     }
4882     return n;
4883   }
4884 
4885   /+
4886   public int stb_vorbis_decode_filename (string filename, int* channels, int* sample_rate, short** output) {
4887     import core.stdc.stdlib : malloc, realloc;
4888 
4889     int data_len, offset, total, limit, error;
4890     short* data;
4891     VorbisDecoder* v = stb_vorbis_open_filename(filename, &error, null);
4892     if (v is null) return -1;
4893     limit = v.vrchannels*4096;
4894     *channels = v.vrchannels;
4895     if (sample_rate) *sample_rate = v.sample_rate;
4896     offset = data_len = 0;
4897     total = limit;
4898     data = cast(short*)malloc(total*(*data).sizeof);
4899     if (data is null) {
4900       stb_vorbis_close(v);
4901       return -2;
4902     }
4903     for (;;) {
4904       int n = stb_vorbis_get_frame_short_interleaved(v, v.vrchannels, data+offset, total-offset);
4905       if (n == 0) break;
4906       data_len += n;
4907       offset += n*v.vrchannels;
4908       if (offset+limit > total) {
4909         short *data2;
4910         total *= 2;
4911         data2 = cast(short*)realloc(data, total*(*data).sizeof);
4912         if (data2 is null) {
4913           import core.stdc.stdlib : free;
4914           free(data);
4915           stb_vorbis_close(v);
4916           return -2;
4917         }
4918         data = data2;
4919       }
4920     }
4921     *output = data;
4922     stb_vorbis_close(v);
4923     return data_len;
4924   }
4925 
4926   public int stb_vorbis_decode_memory (const(void)* mem, int len, int* channels, int* sample_rate, short** output) {
4927     import core.stdc.stdlib : malloc, realloc;
4928 
4929     int data_len, offset, total, limit, error;
4930     short* data;
4931     VorbisDecoder* v = stb_vorbis_open_memory(mem, len, &error, null);
4932     if (v is null) return -1;
4933     limit = v.vrchannels*4096;
4934     *channels = v.vrchannels;
4935     if (sample_rate) *sample_rate = v.sample_rate;
4936     offset = data_len = 0;
4937     total = limit;
4938     data = cast(short*)malloc(total*(*data).sizeof);
4939     if (data is null) {
4940       stb_vorbis_close(v);
4941       return -2;
4942     }
4943     for (;;) {
4944       int n = stb_vorbis_get_frame_short_interleaved(v, v.vrchannels, data+offset, total-offset);
4945       if (n == 0) break;
4946       data_len += n;
4947       offset += n*v.vrchannels;
4948       if (offset+limit > total) {
4949         short *data2;
4950         total *= 2;
4951         data2 = cast(short*)realloc(data, total*(*data).sizeof);
4952         if (data2 is null) {
4953           import core.stdc.stdlib : free;
4954           free(data);
4955           stb_vorbis_close(v);
4956           return -2;
4957         }
4958         data = data2;
4959       }
4960     }
4961     *output = data;
4962     stb_vorbis_close(v);
4963     return data_len;
4964   }
4965 
4966   public int stb_vorbis_get_samples_float_interleaved (VorbisDecoder* this, int channels, float* buffer, int num_floats) {
4967     float** outputs;
4968     int len = num_floats/channels;
4969     int n = 0;
4970     int z = this.vrchannels;
4971     if (z > channels) z = channels;
4972     while (n < len) {
4973       int k = this.channel_buffer_end-this.channel_buffer_start;
4974       if (n+k >= len) k = len-n;
4975       foreach (immutable j; 0..k) {
4976         foreach (immutable i; 0..z) *buffer++ = (this.channel_buffers.ptr[i])[this.channel_buffer_start+j];
4977         foreach (immutable i; z..channels) *buffer++ = 0;
4978       }
4979       n += k;
4980       this.channel_buffer_start += k;
4981       if (n == len) break;
4982       if (!stb_vorbis_get_frame_float(this, null, &outputs)) break;
4983     }
4984     return n;
4985   }
4986   +/
4987 
4988   int getSamplesFloat (int achans, float** buffer, int num_samples) {
4989     import core.stdc.string : memcpy, memset;
4990     // Renamed this from outputs to scopeOutputs to stop override of outer scope's variable
4991     float** scopeOutputs;
4992     int n = 0;
4993     int z = vrchannels;
4994     if (z > achans) z = achans;
4995     while (n < num_samples) {
4996       int k = channel_buffer_end-channel_buffer_start;
4997       if (n+k >= num_samples) k = num_samples-n;
4998       if (k) {
4999         foreach (immutable i; 0..z) memcpy(buffer[i]+n, channel_buffers.ptr[i]+channel_buffer_start, float.sizeof*k);
5000         foreach (immutable i; z..achans) memset(buffer[i]+n, 0, float.sizeof*k);
5001       }
5002       n += k;
5003       channel_buffer_start += k;
5004       if (n == num_samples) break;
5005       if (!getFrameFloat(null, &scopeOutputs)) break;
5006     }
5007     return n;
5008   }
5009 
5010 private: // k8: 'cause i'm evil
5011   enum cmt_len_size = 2;
5012   nothrow /*@trusted*/ @nogc {
5013     public @property bool comment_empty () const pure { return (comment_get_line_len == 0); }
5014 
5015     // 0: error
5016     // includes length itself
5017     uint comment_get_line_len () const pure {
5018       if (comment_data_pos >= comment_size) return 0;
5019       if (comment_size-comment_data_pos < cmt_len_size) return 0;
5020       uint len = comment_data[comment_data_pos];
5021       len += cast(uint)comment_data[comment_data_pos+1]<<8;
5022       return (len >= cmt_len_size && comment_data_pos+len <= comment_size ? len : 0);
5023     }
5024 
5025     public bool comment_rewind () {
5026       comment_data_pos = 0;
5027       for (;;) {
5028         auto len = comment_get_line_len();
5029         if (!len) { comment_data_pos = comment_size; return false; }
5030         if (len != cmt_len_size) return true;
5031         comment_data_pos += len;
5032       }
5033     }
5034 
5035     // true: has something to read after skip
5036     public bool comment_skip () {
5037       comment_data_pos += comment_get_line_len();
5038       for (;;) {
5039         auto len = comment_get_line_len();
5040         if (!len) { comment_data_pos = comment_size; return false; }
5041         if (len != cmt_len_size) break;
5042         comment_data_pos += len;
5043       }
5044       return true;
5045     }
5046 
5047     public const(char)[] comment_line () {
5048       auto len = comment_get_line_len();
5049       if (len < cmt_len_size) return null;
5050       if (len == cmt_len_size) return "";
5051       return (cast(char*)comment_data+comment_data_pos+cmt_len_size)[0..len-cmt_len_size];
5052     }
5053 
5054     public const(char)[] comment_name () {
5055       auto line = comment_line();
5056       if (line.length == 0) return line;
5057       uint epos = 0;
5058       while (epos < line.length && line.ptr[epos] != '=') ++epos;
5059       return (epos < line.length ? line[0..epos] : "");
5060     }
5061 
5062     public const(char)[] comment_value () {
5063       auto line = comment_line();
5064       if (line.length == 0) return line;
5065       uint epos = 0;
5066       while (epos < line.length && line.ptr[epos] != '=') ++epos;
5067       return (epos < line.length ? line[epos+1..$] : line);
5068     }
5069   }
5070 }
5071 
5072 
5073 // ////////////////////////////////////////////////////////////////////////// //
5074 // cool helper to translate C defines
5075 template cmacroFixVars(T...) {
5076   /**
5077    * 64-bit implementation of fasthash
5078    *
5079    * Params:
5080    *   buf =  data buffer
5081    *   seed = the seed
5082    *
5083    * Returns:
5084    *   32-bit or 64-bit hash
5085    */
5086   size_t hashOf (const(void)* buf, size_t len, size_t seed=0) pure nothrow @trusted @nogc {
5087     enum Get8Bytes = q{
5088       cast(ulong)data[0]|
5089       (cast(ulong)data[1]<<8)|
5090       (cast(ulong)data[2]<<16)|
5091       (cast(ulong)data[3]<<24)|
5092       (cast(ulong)data[4]<<32)|
5093       (cast(ulong)data[5]<<40)|
5094       (cast(ulong)data[6]<<48)|
5095       (cast(ulong)data[7]<<56)
5096     };
5097     enum m = 0x880355f21e6d1965UL;
5098     auto data = cast(const(ubyte)*)buf;
5099     ulong h = seed;
5100     ulong t;
5101     foreach (immutable _; 0..len/8) {
5102       version(HasUnalignedOps) {
5103         if (__ctfe) {
5104           t = mixin(Get8Bytes);
5105         } else {
5106           t = *cast(ulong*)data;
5107         }
5108       } else {
5109         t = mixin(Get8Bytes);
5110       }
5111       data += 8;
5112       t ^= t>>23;
5113       t *= 0x2127599bf4325c37UL;
5114       t ^= t>>47;
5115       h ^= t;
5116       h *= m;
5117     }
5118 
5119     h ^= len*m;
5120     t = 0;
5121     switch (len&7) {
5122       case 7: t ^= cast(ulong)data[6]<<48; goto case 6;
5123       case 6: t ^= cast(ulong)data[5]<<40; goto case 5;
5124       case 5: t ^= cast(ulong)data[4]<<32; goto case 4;
5125       case 4: t ^= cast(ulong)data[3]<<24; goto case 3;
5126       case 3: t ^= cast(ulong)data[2]<<16; goto case 2;
5127       case 2: t ^= cast(ulong)data[1]<<8; goto case 1;
5128       case 1: t ^= cast(ulong)data[0]; goto default;
5129       default:
5130         t ^= t>>23;
5131         t *= 0x2127599bf4325c37UL;
5132         t ^= t>>47;
5133         h ^= t;
5134         h *= m;
5135         break;
5136     }
5137 
5138     h ^= h>>23;
5139     h *= 0x2127599bf4325c37UL;
5140     h ^= h>>47;
5141     static if (size_t.sizeof == 4) {
5142       // 32-bit hash
5143       // the following trick converts the 64-bit hashcode to Fermat
5144       // residue, which shall retain information from both the higher
5145       // and lower parts of hashcode.
5146       return cast(size_t)(h-(h>>32));
5147     } else {
5148       return h;
5149     }
5150   }
5151 
5152   string cmacroFixVars (string s, string[] names...) {
5153     assert(T.length == names.length, "cmacroFixVars: names and arguments count mismatch");
5154     enum tmpPfxName = "__temp_prefix__";
5155     string res;
5156     string tmppfx;
5157     uint pos = 0;
5158     // skip empty lines (for pretty printing)
5159     // trim trailing spaces
5160     while (s.length > 0 && s[$-1] <= ' ') s = s[0..$-1];
5161     uint linestpos = 0; // start of the current line
5162     while (pos < s.length) {
5163       if (s[pos] > ' ') break;
5164       if (s[pos] == '\n') linestpos = pos+1;
5165       ++pos;
5166     }
5167     pos = linestpos;
5168     while (pos+2 < s.length) {
5169       int epos = pos;
5170       while (epos+2 < s.length && (s[epos] != '$' || s[epos+1] != '{')) ++epos;
5171       if (epos > pos) {
5172         if (s.length-epos < 3) break;
5173         res ~= s[pos..epos];
5174         pos = epos;
5175       }
5176       assert(s[pos] == '$' && s[pos+1] == '{');
5177       pos += 2;
5178       bool found = false;
5179       if (s.length-pos >= tmpPfxName.length+1 && s[pos+tmpPfxName.length] == '}' 
5180             && s[pos..pos+tmpPfxName.length] == tmpPfxName) {
5181         if (tmppfx.length == 0) {
5182           // generate temporary prefix
5183           auto hash = hashOf(s.ptr, s.length);
5184           immutable char[16] hexChars = "0123456789abcdef";
5185           tmppfx = "_temp_macro_var_";
5186           foreach_reverse (immutable idx; 0..size_t.sizeof*2) {
5187             tmppfx ~= hexChars[hash&0x0f];
5188             hash >>= 4;
5189           }
5190           tmppfx ~= "_";
5191         }
5192         pos += tmpPfxName.length+1;
5193         res ~= tmppfx;
5194         found = true;
5195       } else {
5196         foreach (immutable nidx, string oname; T) {
5197           static assert(oname.length > 0);
5198           if (s.length-pos >= oname.length+1 && s[pos+oname.length] == '}' && s[pos..pos+oname.length] == oname) {
5199             found = true;
5200             pos += oname.length+1;
5201             res ~= names[nidx];
5202             break;
5203           }
5204         }
5205       }
5206       assert(found, "unknown variable in macro");
5207     }
5208     if (pos < s.length) res ~= s[pos..$];
5209     return res;
5210   }
5211 } // This warning will never be fixed
5212 
5213 // ////////////////////////////////////////////////////////////////////////// //
5214 /* Version history
5215     1.09    - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
5216     1.08    - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
5217                            avoid discarding last frame of audio data
5218     1.07    - 2015/01/16 - fixed some warnings, fix mingw, const-correct API
5219                            some more crash fixes when out of memory or with corrupt files
5220     1.06    - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
5221                            some crash fixes when out of memory or with corrupt files
5222     1.05    - 2015/04/19 - don't define __forceinline if it's redundant
5223     1.04    - 2014/08/27 - fix missing const-correct case in API
5224     1.03    - 2014/08/07 - Warning fixes
5225     1.02    - 2014/07/09 - Declare qsort compare function _cdecl on windows
5226     1.01    - 2014/06/18 - fix stb_vorbis_get_samples_float
5227     1.0     - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel
5228                            (API change) report sample rate for decode-full-file funcs
5229     0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
5230     0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
5231     0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
5232     0.99993 - remove assert that fired on legal files with empty tables
5233     0.99992 - rewind-to-start
5234     0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
5235     0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
5236     0.9998 - add a full-decode function with a memory source
5237     0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
5238     0.9996 - query length of vorbis stream in samples/seconds
5239     0.9995 - bugfix to another optimization that only happened in certain files
5240     0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
5241     0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
5242     0.9992 - performance improvement of IMDCT; now performs close to reference implementation
5243     0.9991 - performance improvement of IMDCT
5244     0.999 - (should have been 0.9990) performance improvement of IMDCT
5245     0.998 - no-CRT support from Casey Muratori
5246     0.997 - bugfixes for bugs found by Terje Mathisen
5247     0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
5248     0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
5249     0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
5250     0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
5251     0.992 - fixes for MinGW warning
5252     0.991 - turn fast-float-conversion on by default
5253     0.990 - fix push-mode seek recovery if you seek into the headers
5254     0.98b - fix to bad release of 0.98
5255     0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
5256     0.97 - builds under c++ (typecasting, don't use 'class' keyword)
5257     0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
5258     0.95 - clamping code for 16-bit functions
5259     0.94 - not publically released
5260     0.93 - fixed all-zero-floor case (was decoding garbage)
5261     0.92 - fixed a memory leak
5262     0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
5263     0.90 - first public release
5264 */
5265 
5266 /*
5267 ------------------------------------------------------------------------------
5268 This software is available under 2 licenses -- choose whichever you prefer.
5269 ------------------------------------------------------------------------------
5270 ALTERNATIVE A - MIT License
5271 Copyright (c) 2017 Sean Barrett
5272 Permission is hereby granted, free of charge, to any person obtaining a copy of
5273 this software and associated documentation files (the "Software"), to deal in
5274 the Software without restriction, including without limitation the rights to
5275 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
5276 of the Software, and to permit persons to whom the Software is furnished to do
5277 so, subject to the following conditions:
5278 The above copyright notice and this permission notice shall be included in all
5279 copies or substantial portions of the Software.
5280 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5281 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5282 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5283 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5284 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
5285 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
5286 SOFTWARE.
5287 ------------------------------------------------------------------------------
5288 ALTERNATIVE B - Public Domain (www.unlicense.org)
5289 This is free and unencumbered software released into the public domain.
5290 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
5291 software, either in source code form or as a compiled binary, for any purpose,
5292 commercial or non-commercial, and by any means.
5293 In jurisdictions that recognize copyright laws, the author or authors of this
5294 software dedicate any and all copyright interest in the software to the public
5295 domain. We make this dedication for the benefit of the public at large and to
5296 the detriment of our heirs and successors. We intend this dedication to be an
5297 overt act of relinquishment in perpetuity of all present and future rights to
5298 this software under copyright law.
5299 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5300 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5301 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5302 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
5303 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
5304 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5305 ------------------------------------------------------------------------------
5306 */